2018-08-12 09:29:57 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2019-01-20 19:37:45 +01:00
|
|
|
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
|
|
|
# Copyright (C) 2018-2019 OzzieIsaacs, bodybybuddha, janeczku
|
|
|
|
#
|
|
|
|
# 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/>.
|
|
|
|
|
2019-07-13 20:45:48 +02:00
|
|
|
from __future__ import division, print_function, unicode_literals
|
2018-08-12 09:29:57 +02:00
|
|
|
import sys
|
|
|
|
import os
|
|
|
|
import re
|
2019-07-13 20:45:48 +02:00
|
|
|
import smtplib
|
|
|
|
import socket
|
|
|
|
import time
|
|
|
|
import threading
|
2019-07-14 19:28:32 +02:00
|
|
|
from datetime import datetime
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
from StringIO import StringIO
|
|
|
|
from email.MIMEBase import MIMEBase
|
|
|
|
from email.MIMEMultipart import MIMEMultipart
|
|
|
|
from email.MIMEText import MIMEText
|
|
|
|
except ImportError:
|
|
|
|
from io import StringIO
|
|
|
|
from email.mime.base import MIMEBase
|
|
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
from email.mime.text import MIMEText
|
|
|
|
|
|
|
|
from email import encoders
|
|
|
|
from email.utils import formatdate
|
|
|
|
from email.utils import make_msgid
|
2019-07-13 20:45:48 +02:00
|
|
|
from email.generator import Generator
|
|
|
|
from flask_babel import gettext as _
|
|
|
|
|
|
|
|
from . import logger, config, db, gdriveutils
|
|
|
|
from .subproc_wrapper import process_open
|
|
|
|
|
|
|
|
|
|
|
|
log = logger.create()
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
chunksize = 8192
|
2018-10-03 21:58:37 +02:00
|
|
|
# task 'status' consts
|
2018-08-12 09:29:57 +02:00
|
|
|
STAT_WAITING = 0
|
|
|
|
STAT_FAIL = 1
|
|
|
|
STAT_STARTED = 2
|
|
|
|
STAT_FINISH_SUCCESS = 3
|
2018-10-03 21:58:37 +02:00
|
|
|
#taskType consts
|
2018-08-12 09:29:57 +02:00
|
|
|
TASK_EMAIL = 1
|
|
|
|
TASK_CONVERT = 2
|
2018-08-16 21:17:26 +02:00
|
|
|
TASK_UPLOAD = 3
|
2018-08-29 05:32:30 +02:00
|
|
|
TASK_CONVERT_ANY = 4
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
RET_FAIL = 0
|
|
|
|
RET_SUCCESS = 1
|
|
|
|
|
|
|
|
|
2019-07-14 19:28:32 +02:00
|
|
|
def _get_main_thread():
|
|
|
|
for t in threading.enumerate():
|
|
|
|
if t.__class__.__name__ == '_MainThread':
|
|
|
|
return t
|
|
|
|
raise Exception("main thread not found?!")
|
|
|
|
|
|
|
|
|
2018-08-12 09:29:57 +02:00
|
|
|
# For gdrive download book from gdrive to calibredir (temp dir for books), read contents in both cases and append
|
|
|
|
# it in MIME Base64 encoded to
|
|
|
|
def get_attachment(bookpath, filename):
|
|
|
|
"""Get file as MIMEBase message"""
|
2019-07-13 20:45:48 +02:00
|
|
|
calibrepath = config.config_calibre_dir
|
|
|
|
if config.config_use_google_drive:
|
|
|
|
df = gdriveutils.getFileFromEbooksFolder(bookpath, filename)
|
2018-08-12 09:29:57 +02:00
|
|
|
if df:
|
|
|
|
datafile = os.path.join(calibrepath, bookpath, filename)
|
|
|
|
if not os.path.exists(os.path.join(calibrepath, bookpath)):
|
|
|
|
os.makedirs(os.path.join(calibrepath, bookpath))
|
|
|
|
df.GetContentFile(datafile)
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
file_ = open(datafile, 'rb')
|
|
|
|
data = file_.read()
|
|
|
|
file_.close()
|
|
|
|
os.remove(datafile)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
file_ = open(os.path.join(calibrepath, bookpath, filename), 'rb')
|
|
|
|
data = file_.read()
|
|
|
|
file_.close()
|
2018-11-18 17:09:13 +01:00
|
|
|
except IOError as e:
|
2019-07-13 20:45:48 +02:00
|
|
|
log.exception(e) # traceback.print_exc()
|
|
|
|
log.error(u'The requested file could not be read. Maybe wrong permissions?')
|
2018-08-12 09:29:57 +02:00
|
|
|
return None
|
|
|
|
|
|
|
|
attachment = MIMEBase('application', 'octet-stream')
|
|
|
|
attachment.set_payload(data)
|
|
|
|
encoders.encode_base64(attachment)
|
|
|
|
attachment.add_header('Content-Disposition', 'attachment',
|
|
|
|
filename=filename)
|
|
|
|
return attachment
|
|
|
|
|
|
|
|
|
|
|
|
# Class for sending email with ability to get current progress
|
2018-08-14 17:38:38 +02:00
|
|
|
class emailbase():
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
transferSize = 0
|
|
|
|
progress = 0
|
|
|
|
|
|
|
|
def data(self, msg):
|
|
|
|
self.transferSize = len(msg)
|
|
|
|
(code, resp) = smtplib.SMTP.data(self, msg)
|
|
|
|
self.progress = 0
|
|
|
|
return (code, resp)
|
|
|
|
|
|
|
|
def send(self, strg):
|
|
|
|
"""Send `strg' to the server."""
|
2019-07-13 20:45:48 +02:00
|
|
|
log.debug('send: %r', strg[:300])
|
2018-08-12 09:29:57 +02:00
|
|
|
if hasattr(self, 'sock') and self.sock:
|
|
|
|
try:
|
|
|
|
if self.transferSize:
|
|
|
|
lock=threading.Lock()
|
|
|
|
lock.acquire()
|
|
|
|
self.transferSize = len(strg)
|
|
|
|
lock.release()
|
|
|
|
for i in range(0, self.transferSize, chunksize):
|
2019-01-14 20:27:53 +01:00
|
|
|
if isinstance(strg, bytes):
|
2018-08-13 19:43:50 +02:00
|
|
|
self.sock.send((strg[i:i+chunksize]))
|
|
|
|
else:
|
|
|
|
self.sock.send((strg[i:i + chunksize]).encode('utf-8'))
|
2018-08-12 09:29:57 +02:00
|
|
|
lock.acquire()
|
|
|
|
self.progress = i
|
|
|
|
lock.release()
|
|
|
|
else:
|
2018-08-13 19:43:50 +02:00
|
|
|
self.sock.sendall(strg.encode('utf-8'))
|
2018-08-12 09:29:57 +02:00
|
|
|
except socket.error:
|
|
|
|
self.close()
|
|
|
|
raise smtplib.SMTPServerDisconnected('Server not connected')
|
|
|
|
else:
|
|
|
|
raise smtplib.SMTPServerDisconnected('please run connect() first')
|
|
|
|
|
2019-07-13 20:45:48 +02:00
|
|
|
@classmethod
|
|
|
|
def _print_debug(self, *args):
|
|
|
|
log.debug(args)
|
|
|
|
|
2018-08-12 09:29:57 +02:00
|
|
|
def getTransferStatus(self):
|
|
|
|
if self.transferSize:
|
|
|
|
lock2 = threading.Lock()
|
|
|
|
lock2.acquire()
|
2018-08-16 21:17:26 +02:00
|
|
|
value = int((float(self.progress) / float(self.transferSize))*100)
|
2018-08-12 09:29:57 +02:00
|
|
|
lock2.release()
|
|
|
|
return str(value) + ' %'
|
|
|
|
else:
|
|
|
|
return "100 %"
|
|
|
|
|
|
|
|
|
2018-08-14 17:38:38 +02:00
|
|
|
# Class for sending email with ability to get current progress, derived from emailbase class
|
|
|
|
class email(emailbase, smtplib.SMTP):
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
smtplib.SMTP.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
# Class for sending ssl encrypted email with ability to get current progress, , derived from emailbase class
|
|
|
|
class email_SSL(emailbase, smtplib.SMTP_SSL):
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
smtplib.SMTP_SSL.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
#Class for all worker tasks in the background
|
|
|
|
class WorkerThread(threading.Thread):
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
self.status = 0
|
|
|
|
self.current = 0
|
|
|
|
self.last = 0
|
|
|
|
self.queue = list()
|
|
|
|
self.UIqueue = list()
|
2019-07-14 19:28:32 +02:00
|
|
|
self.asyncSMTP = None
|
2018-08-12 09:29:57 +02:00
|
|
|
self.id = 0
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock = threading.Lock()
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
# Main thread loop starting the different tasks
|
|
|
|
def run(self):
|
2019-07-14 19:28:32 +02:00
|
|
|
main_thread = _get_main_thread()
|
|
|
|
while main_thread.is_alive():
|
2019-11-26 08:19:03 +01:00
|
|
|
try:
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2019-11-26 08:19:03 +01:00
|
|
|
if self.current != self.last:
|
|
|
|
index = self.current
|
|
|
|
self.doLock.release()
|
|
|
|
if self.queue[index]['taskType'] == TASK_EMAIL:
|
|
|
|
self._send_raw_email()
|
|
|
|
if self.queue[index]['taskType'] == TASK_CONVERT:
|
|
|
|
self._convert_any_format()
|
|
|
|
if self.queue[index]['taskType'] == TASK_CONVERT_ANY:
|
|
|
|
self._convert_any_format()
|
|
|
|
# TASK_UPLOAD is handled implicitly
|
|
|
|
self.doLock.acquire()
|
|
|
|
self.current += 1
|
|
|
|
if self.current > self.last:
|
|
|
|
self.current = self.last
|
|
|
|
self.doLock.release()
|
|
|
|
else:
|
|
|
|
self.doLock.release()
|
|
|
|
except Exception as e:
|
2019-11-26 10:46:06 +01:00
|
|
|
log.exception(e)
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2019-07-14 19:28:32 +02:00
|
|
|
if main_thread.is_alive():
|
|
|
|
time.sleep(1)
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
def get_send_status(self):
|
|
|
|
if self.asyncSMTP:
|
|
|
|
return self.asyncSMTP.getTransferStatus()
|
|
|
|
else:
|
|
|
|
return "0 %"
|
|
|
|
|
2018-11-03 13:43:38 +01:00
|
|
|
def _delete_completed_tasks(self):
|
2018-08-12 09:29:57 +02:00
|
|
|
for index, task in reversed(list(enumerate(self.UIqueue))):
|
|
|
|
if task['progress'] == "100 %":
|
|
|
|
# delete tasks
|
|
|
|
self.queue.pop(index)
|
|
|
|
self.UIqueue.pop(index)
|
|
|
|
# if we are deleting entries before the current index, adjust the index
|
2019-12-29 13:54:52 +01:00
|
|
|
if index <= self.current and self.current:
|
2019-11-26 08:19:03 +01:00
|
|
|
self.current -= 1
|
2018-08-12 09:29:57 +02:00
|
|
|
self.last = len(self.queue)
|
|
|
|
|
|
|
|
def get_taskstatus(self):
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2018-08-12 09:29:57 +02:00
|
|
|
if self.current < len(self.queue):
|
2018-11-03 13:43:38 +01:00
|
|
|
if self.UIqueue[self.current]['stat'] == STAT_STARTED:
|
2018-10-03 21:58:37 +02:00
|
|
|
if self.queue[self.current]['taskType'] == TASK_EMAIL:
|
2018-08-12 09:29:57 +02:00
|
|
|
self.UIqueue[self.current]['progress'] = self.get_send_status()
|
2019-06-30 11:20:36 +02:00
|
|
|
self.UIqueue[self.current]['formRuntime'] = datetime.now() - self.queue[self.current]['starttime']
|
|
|
|
self.UIqueue[self.current]['rt'] = self.UIqueue[self.current]['formRuntime'].days*24*60 \
|
|
|
|
+ self.UIqueue[self.current]['formRuntime'].seconds \
|
|
|
|
+ self.UIqueue[self.current]['formRuntime'].microseconds
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2018-08-12 09:29:57 +02:00
|
|
|
return self.UIqueue
|
2018-08-19 10:14:20 +02:00
|
|
|
|
2018-11-03 13:43:38 +01:00
|
|
|
def _convert_any_format(self):
|
2018-08-12 09:29:57 +02:00
|
|
|
# convert book, and upload in case of google drive
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2019-07-22 18:28:45 +02:00
|
|
|
index = self.current
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2019-07-22 18:28:45 +02:00
|
|
|
self.UIqueue[index]['stat'] = STAT_STARTED
|
|
|
|
self.queue[index]['starttime'] = datetime.now()
|
2019-11-26 08:19:03 +01:00
|
|
|
self.UIqueue[index]['formStarttime'] = self.queue[index]['starttime']
|
2019-07-22 18:28:45 +02:00
|
|
|
curr_task = self.queue[index]['taskType']
|
2018-11-03 13:43:38 +01:00
|
|
|
filename = self._convert_ebook_format()
|
2018-08-31 15:00:22 +02:00
|
|
|
if filename:
|
2019-07-13 20:45:48 +02:00
|
|
|
if config.config_use_google_drive:
|
|
|
|
gdriveutils.updateGdriveCalibreFromLocal()
|
2018-08-31 15:00:22 +02:00
|
|
|
if curr_task == TASK_CONVERT:
|
2019-07-22 18:28:45 +02:00
|
|
|
self.add_email(self.queue[index]['settings']['subject'], self.queue[index]['path'],
|
|
|
|
filename, self.queue[index]['settings'], self.queue[index]['kindle'],
|
|
|
|
self.UIqueue[index]['user'], self.queue[index]['title'],
|
|
|
|
self.queue[index]['settings']['body'])
|
2018-08-12 09:29:57 +02:00
|
|
|
|
2018-11-03 13:43:38 +01:00
|
|
|
def _convert_ebook_format(self):
|
2018-08-12 09:29:57 +02:00
|
|
|
error_message = None
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2019-07-22 18:28:45 +02:00
|
|
|
index = self.current
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2019-07-22 18:28:45 +02:00
|
|
|
file_path = self.queue[index]['file_path']
|
|
|
|
bookid = self.queue[index]['bookid']
|
|
|
|
format_old_ext = u'.' + self.queue[index]['settings']['old_book_format'].lower()
|
|
|
|
format_new_ext = u'.' + self.queue[index]['settings']['new_book_format'].lower()
|
2018-10-03 21:58:37 +02:00
|
|
|
|
2018-09-14 16:35:01 +02:00
|
|
|
# check to see if destination format already exists -
|
2018-09-14 03:24:21 +02:00
|
|
|
# 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):
|
2019-07-13 20:45:48 +02:00
|
|
|
log.info("Book id %d already converted to %s", bookid, format_new_ext)
|
|
|
|
cur_book = db.session.query(db.Books).filter(db.Books.id == bookid).first()
|
2019-07-22 18:28:45 +02:00
|
|
|
self.queue[index]['path'] = file_path
|
|
|
|
self.queue[index]['title'] = cur_book.title
|
2018-09-14 20:36:45 +02:00
|
|
|
self._handleSuccess()
|
2018-09-14 03:24:21 +02:00
|
|
|
return file_path + format_new_ext
|
|
|
|
else:
|
2019-07-13 20:45:48 +02:00
|
|
|
log.info("Book id %d - target format of %s does not exist. Moving forward with convert.", bookid, format_new_ext)
|
2018-10-03 21:58:37 +02:00
|
|
|
|
2018-08-31 15:00:22 +02:00
|
|
|
# check if converter-executable is existing
|
2019-07-13 20:45:48 +02:00
|
|
|
if not os.path.exists(config.config_converterpath):
|
2018-11-03 13:43:38 +01:00
|
|
|
# ToDo Text is not translated
|
2019-07-13 20:45:48 +02:00
|
|
|
self._handleError(u"Convertertool %s not found" % config.config_converterpath)
|
2018-08-16 21:17:26 +02:00
|
|
|
return
|
2018-10-03 21:58:37 +02:00
|
|
|
|
2018-08-16 21:17:26 +02:00
|
|
|
try:
|
|
|
|
# check which converter to use kindlegen is "1"
|
2018-08-31 15:00:22 +02:00
|
|
|
if format_old_ext == '.epub' and format_new_ext == '.mobi':
|
2019-07-13 20:45:48 +02:00
|
|
|
if config.config_ebookconverter == 1:
|
|
|
|
'''if os.name == 'nt':
|
|
|
|
command = config.config_converterpath + u' "' + file_path + u'.epub"'
|
2018-08-31 15:00:22 +02:00
|
|
|
if sys.version_info < (3, 0):
|
|
|
|
command = command.encode(sys.getfilesystemencoding())
|
2019-07-13 20:45:48 +02:00
|
|
|
else:'''
|
|
|
|
command = [config.config_converterpath, file_path + u'.epub']
|
|
|
|
quotes = [1]
|
|
|
|
if config.config_ebookconverter == 2:
|
2018-08-22 21:24:28 +02:00
|
|
|
# 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
|
2018-08-31 15:00:22 +02:00
|
|
|
# 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
|
2019-07-13 20:45:48 +02:00
|
|
|
quotes = [1,2]
|
|
|
|
'''if os.name == 'nt':
|
|
|
|
command = config.config_converterpath + u' "' + file_path + format_old_ext + u'" "' + \
|
|
|
|
file_path + format_new_ext + u'" ' + config.config_calibre
|
2018-08-22 21:24:28 +02:00
|
|
|
if sys.version_info < (3, 0):
|
|
|
|
command = command.encode(sys.getfilesystemencoding())
|
2019-07-13 20:45:48 +02:00
|
|
|
else:'''
|
|
|
|
command = [config.config_converterpath, (file_path + format_old_ext),
|
|
|
|
(file_path + format_new_ext)]
|
2019-07-22 18:28:45 +02:00
|
|
|
quotes_index = 3
|
2019-07-13 20:45:48 +02:00
|
|
|
if config.config_calibre:
|
|
|
|
parameters = config.config_calibre.split(" ")
|
|
|
|
for param in parameters:
|
|
|
|
command.append(param)
|
2019-07-22 18:28:45 +02:00
|
|
|
quotes.append(quotes_index)
|
|
|
|
quotes_index += 1
|
2019-07-13 20:45:48 +02:00
|
|
|
p = process_open(command, quotes)
|
|
|
|
# p = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
|
2018-08-18 08:48:42 +02:00
|
|
|
except OSError as e:
|
2018-09-08 12:28:48 +02:00
|
|
|
self._handleError(_(u"Ebook-converter failed: %(error)s", error=e))
|
2018-08-16 21:17:26 +02:00
|
|
|
return
|
2018-08-31 15:00:22 +02:00
|
|
|
|
2019-07-13 20:45:48 +02:00
|
|
|
if config.config_ebookconverter == 1:
|
2018-08-16 21:17:26 +02:00
|
|
|
nextline = p.communicate()[0]
|
|
|
|
# Format of error message (kindlegen translates its output texts):
|
|
|
|
# Error(prcgen):E23006: Language not recognized in metadata.The dc:Language field is mandatory.Aborting.
|
2019-07-14 19:28:32 +02:00
|
|
|
conv_error = re.search(r".*\(.*\):(E\d+):\s(.*)", nextline, re.MULTILINE)
|
2018-08-18 08:48:42 +02:00
|
|
|
# If error occoures, store error message for logfile
|
2018-08-16 21:17:26 +02:00
|
|
|
if conv_error:
|
|
|
|
error_message = _(u"Kindlegen failed with Error %(error)s. Message: %(message)s",
|
|
|
|
error=conv_error.group(1), message=conv_error.group(2).strip())
|
2019-07-13 20:45:48 +02:00
|
|
|
log.debug("convert_kindlegen: %s", nextline)
|
2018-08-16 21:17:26 +02:00
|
|
|
else:
|
|
|
|
while p.poll() is None:
|
|
|
|
nextline = p.stdout.readline()
|
2018-08-18 08:48:42 +02:00
|
|
|
if os.name == 'nt' and sys.version_info < (3, 0):
|
|
|
|
nextline = nextline.decode('windows-1252')
|
2019-07-13 20:45:48 +02:00
|
|
|
elif os.name == 'posix' and sys.version_info < (3, 0):
|
|
|
|
nextline = nextline.decode('utf-8')
|
|
|
|
log.debug(nextline.strip('\r\n'))
|
2018-08-18 08:48:42 +02:00
|
|
|
# parse progress string from calibre-converter
|
2019-07-14 19:28:32 +02:00
|
|
|
progress = re.search(r"(\d+)%\s.*", nextline)
|
2018-08-16 21:17:26 +02:00
|
|
|
if progress:
|
2019-07-22 18:28:45 +02:00
|
|
|
self.UIqueue[index]['progress'] = progress.group(1) + ' %'
|
2018-08-16 21:17:26 +02:00
|
|
|
|
2018-08-31 15:00:22 +02:00
|
|
|
# process returncode
|
2018-08-16 21:17:26 +02:00
|
|
|
check = p.returncode
|
2019-06-30 11:20:36 +02:00
|
|
|
calibre_traceback = p.stderr.readlines()
|
|
|
|
for ele in calibre_traceback:
|
2019-07-13 20:45:48 +02:00
|
|
|
if sys.version_info < (3, 0):
|
|
|
|
ele = ele.decode('utf-8')
|
|
|
|
log.debug(ele.strip('\n'))
|
2019-06-30 11:20:36 +02:00
|
|
|
if not ele.startswith('Traceback') and not ele.startswith(' File'):
|
|
|
|
error_message = "Calibre failed with error: %s" % ele.strip('\n')
|
2018-08-18 08:48:42 +02:00
|
|
|
|
2018-08-16 21:17:26 +02:00
|
|
|
# kindlegen returncodes
|
|
|
|
# 0 = Info(prcgen):I1036: Mobi file built successfully
|
|
|
|
# 1 = Info(prcgen):I1037: Mobi file built with WARNINGS!
|
2018-08-19 10:14:20 +02:00
|
|
|
# 2 = Info(prcgen):I1038: MOBI file could not be generated because of errors!
|
2019-07-13 20:45:48 +02:00
|
|
|
if (check < 2 and config.config_ebookconverter == 1) or \
|
|
|
|
(check == 0 and config.config_ebookconverter == 2):
|
|
|
|
cur_book = db.session.query(db.Books).filter(db.Books.id == bookid).first()
|
2018-09-02 08:54:46 +02:00
|
|
|
if os.path.isfile(file_path + format_new_ext):
|
2019-07-13 20:45:48 +02:00
|
|
|
new_format = db.Data(name=cur_book.data[0].name,
|
2019-07-22 18:28:45 +02:00
|
|
|
book_format=self.queue[index]['settings']['new_book_format'].upper(),
|
2018-09-02 08:54:46 +02:00
|
|
|
book=bookid, uncompressed_size=os.path.getsize(file_path + format_new_ext))
|
|
|
|
cur_book.data.append(new_format)
|
2019-07-13 20:45:48 +02:00
|
|
|
db.session.commit()
|
2019-07-22 18:28:45 +02:00
|
|
|
self.queue[index]['path'] = cur_book.path
|
|
|
|
self.queue[index]['title'] = cur_book.title
|
2019-07-13 20:45:48 +02:00
|
|
|
if config.config_use_google_drive:
|
2018-09-02 08:54:46 +02:00
|
|
|
os.remove(file_path + format_old_ext)
|
2018-09-14 20:36:45 +02:00
|
|
|
self._handleSuccess()
|
2018-09-02 08:54:46 +02:00
|
|
|
return file_path + format_new_ext
|
|
|
|
else:
|
|
|
|
error_message = format_new_ext.upper() + ' format not found on disk'
|
2019-07-13 20:45:48 +02:00
|
|
|
log.info("ebook converter failed with error while converting book")
|
2018-09-02 08:54:46 +02:00
|
|
|
if not error_message:
|
|
|
|
error_message = 'Ebook converter failed with unknown error'
|
|
|
|
self._handleError(error_message)
|
|
|
|
return
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
|
2018-10-03 21:58:37 +02:00
|
|
|
def add_convert(self, file_path, bookid, user_name, taskMessage, settings, kindle_mail=None):
|
2019-11-26 08:19:03 +01:00
|
|
|
self.doLock.acquire()
|
2018-08-12 09:29:57 +02:00
|
|
|
if self.last >= 20:
|
2018-11-03 13:43:38 +01:00
|
|
|
self._delete_completed_tasks()
|
2018-08-12 09:29:57 +02:00
|
|
|
# progress, runtime, and status = 0
|
|
|
|
self.id += 1
|
2018-08-31 15:00:22 +02:00
|
|
|
task = TASK_CONVERT_ANY
|
|
|
|
if kindle_mail:
|
|
|
|
task = TASK_CONVERT
|
|
|
|
self.queue.append({'file_path':file_path, 'bookid':bookid, 'starttime': 0, 'kindle': kindle_mail,
|
2018-11-03 13:43:38 +01:00
|
|
|
'taskType': task, 'settings':settings})
|
|
|
|
self.UIqueue.append({'user': user_name, 'formStarttime': '', 'progress': " 0 %", 'taskMess': taskMessage,
|
|
|
|
'runtime': '0 s', 'stat': STAT_WAITING,'id': self.id, 'taskType': task } )
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
self.last=len(self.queue)
|
2019-11-26 08:19:03 +01:00
|
|
|
self.doLock.release()
|
2018-08-12 09:29:57 +02:00
|
|
|
|
2018-10-03 21:58:37 +02:00
|
|
|
def add_email(self, subject, filepath, attachment, settings, recipient, user_name, taskMessage,
|
2018-11-03 13:43:38 +01:00
|
|
|
text):
|
2018-08-12 09:29:57 +02:00
|
|
|
# if more than 20 entries in the list, clean the list
|
2019-11-26 08:19:03 +01:00
|
|
|
self.doLock.acquire()
|
2018-08-12 09:29:57 +02:00
|
|
|
if self.last >= 20:
|
2018-11-03 13:43:38 +01:00
|
|
|
self._delete_completed_tasks()
|
2018-08-12 09:29:57 +02:00
|
|
|
# progress, runtime, and status = 0
|
2018-08-31 15:00:22 +02:00
|
|
|
self.id += 1
|
2018-08-12 09:29:57 +02:00
|
|
|
self.queue.append({'subject':subject, 'attachment':attachment, 'filepath':filepath,
|
|
|
|
'settings':settings, 'recipent':recipient, 'starttime': 0,
|
2018-11-03 13:43:38 +01:00
|
|
|
'taskType': TASK_EMAIL, 'text':text})
|
|
|
|
self.UIqueue.append({'user': user_name, 'formStarttime': '', 'progress': " 0 %", 'taskMess': taskMessage,
|
|
|
|
'runtime': '0 s', 'stat': STAT_WAITING,'id': self.id, 'taskType': TASK_EMAIL })
|
2018-08-12 09:29:57 +02:00
|
|
|
self.last=len(self.queue)
|
2019-11-26 08:19:03 +01:00
|
|
|
self.doLock.release()
|
2018-08-12 09:29:57 +02:00
|
|
|
|
2018-10-03 21:58:37 +02:00
|
|
|
def add_upload(self, user_name, taskMessage):
|
2018-08-16 21:17:26 +02:00
|
|
|
# if more than 20 entries in the list, clean the list
|
2019-11-26 08:19:03 +01:00
|
|
|
self.doLock.acquire()
|
|
|
|
|
|
|
|
|
2018-08-16 21:17:26 +02:00
|
|
|
if self.last >= 20:
|
2018-11-03 13:43:38 +01:00
|
|
|
self._delete_completed_tasks()
|
2018-08-16 21:17:26 +02:00
|
|
|
# progress=100%, runtime=0, and status finished
|
2019-12-08 09:40:54 +01:00
|
|
|
log.debug("Last " + str(self.last))
|
|
|
|
log.debug("Current " + str(self.current))
|
|
|
|
log.debug("id" + str(self.id))
|
2019-11-26 08:19:03 +01:00
|
|
|
|
2018-08-31 15:00:22 +02:00
|
|
|
self.id += 1
|
2019-11-26 08:19:03 +01:00
|
|
|
starttime = datetime.now()
|
|
|
|
self.queue.append({'starttime': starttime, 'taskType': TASK_UPLOAD})
|
|
|
|
self.UIqueue.append({'user': user_name, 'formStarttime': starttime, 'progress': "100 %", 'taskMess': taskMessage,
|
2018-11-03 13:43:38 +01:00
|
|
|
'runtime': '0 s', 'stat': STAT_FINISH_SUCCESS,'id': self.id, 'taskType': TASK_UPLOAD})
|
2018-08-16 21:17:26 +02:00
|
|
|
self.last=len(self.queue)
|
2019-11-26 08:19:03 +01:00
|
|
|
self.doLock.release()
|
2018-08-29 05:32:30 +02:00
|
|
|
|
2018-11-03 13:43:38 +01:00
|
|
|
def _send_raw_email(self):
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2019-07-22 18:28:45 +02:00
|
|
|
index = self.current
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2019-07-22 18:28:45 +02:00
|
|
|
self.queue[index]['starttime'] = datetime.now()
|
|
|
|
self.UIqueue[index]['formStarttime'] = self.queue[index]['starttime']
|
|
|
|
self.UIqueue[index]['stat'] = STAT_STARTED
|
|
|
|
obj=self.queue[index]
|
2018-08-12 09:29:57 +02:00
|
|
|
# create MIME message
|
|
|
|
msg = MIMEMultipart()
|
2019-07-22 18:28:45 +02:00
|
|
|
msg['Subject'] = self.queue[index]['subject']
|
2018-08-12 09:29:57 +02:00
|
|
|
msg['Message-Id'] = make_msgid('calibre-web')
|
|
|
|
msg['Date'] = formatdate(localtime=True)
|
2019-07-22 18:28:45 +02:00
|
|
|
text = self.queue[index]['text']
|
2018-08-12 09:29:57 +02:00
|
|
|
msg.attach(MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8'))
|
|
|
|
if obj['attachment']:
|
|
|
|
result = get_attachment(obj['filepath'], obj['attachment'])
|
|
|
|
if result:
|
|
|
|
msg.attach(result)
|
|
|
|
else:
|
2018-08-16 21:17:26 +02:00
|
|
|
self._handleError(u"Attachment not found")
|
2018-08-12 09:29:57 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
msg['From'] = obj['settings']["mail_from"]
|
|
|
|
msg['To'] = obj['recipent']
|
|
|
|
|
|
|
|
use_ssl = int(obj['settings'].get('mail_use_ssl', 0))
|
|
|
|
try:
|
2018-09-02 08:41:09 +02:00
|
|
|
# convert MIME message to string
|
|
|
|
fp = StringIO()
|
|
|
|
gen = Generator(fp, mangle_from_=False)
|
|
|
|
gen.flatten(msg)
|
|
|
|
msg = fp.getvalue()
|
|
|
|
|
|
|
|
# send email
|
2018-08-12 09:29:57 +02:00
|
|
|
timeout = 600 # set timeout to 5mins
|
|
|
|
|
2019-07-13 20:45:48 +02:00
|
|
|
# redirect output to logfile on python2 pn python3 debugoutput is caught with overwritten
|
|
|
|
# _print_debug function
|
|
|
|
if sys.version_info < (3, 0):
|
|
|
|
org_smtpstderr = smtplib.stderr
|
|
|
|
smtplib.stderr = logger.StderrLogger('worker.smtp')
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
if use_ssl == 2:
|
2019-09-17 18:25:17 +02:00
|
|
|
self.asyncSMTP = email_SSL(obj['settings']["mail_server"], obj['settings']["mail_port"], timeout=timeout)
|
2018-08-12 09:29:57 +02:00
|
|
|
else:
|
2019-09-17 18:25:17 +02:00
|
|
|
self.asyncSMTP = email(obj['settings']["mail_server"], obj['settings']["mail_port"], timeout=timeout)
|
2018-08-12 09:29:57 +02:00
|
|
|
|
|
|
|
# link to logginglevel
|
2019-07-13 20:45:48 +02:00
|
|
|
if logger.is_debug_enabled():
|
2018-08-12 09:29:57 +02:00
|
|
|
self.asyncSMTP.set_debuglevel(1)
|
|
|
|
if use_ssl == 1:
|
|
|
|
self.asyncSMTP.starttls()
|
|
|
|
if obj['settings']["mail_password"]:
|
|
|
|
self.asyncSMTP.login(str(obj['settings']["mail_login"]), str(obj['settings']["mail_password"]))
|
|
|
|
self.asyncSMTP.sendmail(obj['settings']["mail_from"], obj['recipent'], msg)
|
|
|
|
self.asyncSMTP.quit()
|
2018-09-14 20:36:45 +02:00
|
|
|
self._handleSuccess()
|
2019-07-13 20:45:48 +02:00
|
|
|
|
|
|
|
if sys.version_info < (3, 0):
|
|
|
|
smtplib.stderr = org_smtpstderr
|
2018-08-12 09:29:57 +02:00
|
|
|
|
2018-09-02 08:41:09 +02:00
|
|
|
except (MemoryError) as e:
|
|
|
|
self._handleError(u'Error sending email: ' + e.message)
|
|
|
|
return None
|
2019-04-14 14:08:49 +02:00
|
|
|
except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
|
2018-11-03 13:43:38 +01:00
|
|
|
if hasattr(e, "smtp_error"):
|
2019-04-14 14:08:49 +02:00
|
|
|
text = e.smtp_error.decode('utf-8').replace("\n",'. ')
|
2019-01-14 20:27:53 +01:00
|
|
|
elif hasattr(e, "message"):
|
|
|
|
text = e.message
|
2018-11-03 13:43:38 +01:00
|
|
|
else:
|
|
|
|
text = ''
|
|
|
|
self._handleError(u'Error sending email: ' + text)
|
2018-08-16 21:17:26 +02:00
|
|
|
return None
|
2018-09-02 08:41:09 +02:00
|
|
|
except (socket.error) as e:
|
|
|
|
self._handleError(u'Error sending email: ' + e.strerror)
|
|
|
|
return None
|
|
|
|
|
2018-08-16 21:17:26 +02:00
|
|
|
def _handleError(self, error_message):
|
2019-07-13 20:45:48 +02:00
|
|
|
log.error(error_message)
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2019-07-22 18:28:45 +02:00
|
|
|
index = self.current
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2019-07-22 18:28:45 +02:00
|
|
|
self.UIqueue[index]['stat'] = STAT_FAIL
|
|
|
|
self.UIqueue[index]['progress'] = "100 %"
|
2019-11-26 08:19:03 +01:00
|
|
|
self.UIqueue[index]['formRuntime'] = datetime.now() - self.queue[index]['starttime']
|
2019-07-22 18:28:45 +02:00
|
|
|
self.UIqueue[index]['message'] = error_message
|
2018-08-16 21:17:26 +02:00
|
|
|
|
2018-09-14 20:36:45 +02:00
|
|
|
def _handleSuccess(self):
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.acquire()
|
2019-07-22 18:28:45 +02:00
|
|
|
index = self.current
|
2019-07-23 19:09:16 +02:00
|
|
|
self.doLock.release()
|
2019-07-22 18:28:45 +02:00
|
|
|
self.UIqueue[index]['stat'] = STAT_FINISH_SUCCESS
|
|
|
|
self.UIqueue[index]['progress'] = "100 %"
|
2019-11-26 08:19:03 +01:00
|
|
|
self.UIqueue[index]['formRuntime'] = datetime.now() - self.queue[index]['starttime']
|
2019-07-14 19:28:32 +02:00
|
|
|
|
|
|
|
|
|
|
|
_worker = WorkerThread()
|
|
|
|
_worker.start()
|
|
|
|
|
|
|
|
|
|
|
|
def get_taskstatus():
|
|
|
|
return _worker.get_taskstatus()
|
|
|
|
|
|
|
|
|
|
|
|
def add_email(subject, filepath, attachment, settings, recipient, user_name, taskMessage, text):
|
|
|
|
return _worker.add_email(subject, filepath, attachment, settings, recipient, user_name, taskMessage, text)
|
|
|
|
|
|
|
|
|
|
|
|
def add_upload(user_name, taskMessage):
|
|
|
|
return _worker.add_upload(user_name, taskMessage)
|
|
|
|
|
|
|
|
|
|
|
|
def add_convert(file_path, bookid, user_name, taskMessage, settings, kindle_mail=None):
|
|
|
|
return _worker.add_convert(file_path, bookid, user_name, taskMessage, settings, kindle_mail)
|