Skip to content

Commit

Permalink
Restructuring code
Browse files Browse the repository at this point in the history
  • Loading branch information
pirtim committed Mar 27, 2017
1 parent 0d56bbf commit 5627b27
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 55 deletions.
32 changes: 13 additions & 19 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#shell messes up escaping of spaced filenames to the script
# popen = partial(subprocess.Popen, shell=True)
prints = partial(prints, '{}:'.format(PLUGINNAME)) # for easy printing
printsd = partial(prints, '{}:'.format('DEBUG')) # for DEBUG msg

# -- Calibre Plugin class --
class DJVUmaker(FileTypePlugin, InterfaceActionBase): #multiple inheritance for gui hooks!
Expand All @@ -57,7 +58,6 @@ def __init__(self, *args, **kwargs):
# REGISTERED_BACKENDS = ['pdf2djvu', 'djvudigital']
# Set default preferences
DEFAULT_STORE_VALUES = {}
DEFAULT_STORE_VALUES['installed'] = []
for item in self.REGISTERED_BACKENDS:
DEFAULT_STORE_VALUES[item] = {'flags' : [], 'installed' : False}
if 'djvudigital' in self.REGISTERED_BACKENDS:
Expand Down Expand Up @@ -94,7 +94,7 @@ def customization_help(self, gui=False):
def cli_main(self, args):
'''Handles plugin cli interface'''
args = args[1:] # args[0] = PLUGINNAME
prints('cli_main enter: args: ', args) # DEBUG
printsd('cli_main enter: args: ', args) # DEBUG
from calibre_plugins.djvumaker.utils import create_cli_parser
parser = create_cli_parser(self, PLUGINNAME, PLUGINVER_DOT)
if len(args) == 0:
Expand All @@ -104,7 +104,7 @@ def cli_main(self, args):
options.func(options)

def cli_backend(self, args):
prints('cli_backend enter: plugin_prefs:', self.plugin_prefs)
printsd('cli_backend enter: plugin_prefs:', self.plugin_prefs)
if args.command == 'install':
self.cli_install_backend(args)
elif args.command == 'set':
Expand All @@ -113,7 +113,7 @@ def cli_backend(self, args):
raise Exception('Command not recognized.')

def cli_install_backend(self, args):
prints('cli_install_backend enter: args.backend:', args.backend)
printsd('cli_install_backend enter: args.backend:', args.backend)
if not args.backend:
installed_backend = [k for k, v in {
item : self.plugin_prefs[item]['installed'] for item in self.REGISTERED_BACKENDS
Expand Down Expand Up @@ -143,14 +143,8 @@ def cli_install_backend(self, args):
# TODO: inherit from JSONConfig and make better implementation for defaults
elif args.backend == 'pdf2djvu':
# raise NotImplementedError
# on python 3.3 exist os.which
import urllib
import urllib2
import urlparse
from calibre_plugins.djvumaker.utils import install_pdf2djvu
result = install_pdf2djvu(log=prints)

# unzip it folder plugins
# path?
# TODO: give flag where to installed_backend
# TODO: ask if add to path?
Expand All @@ -173,9 +167,9 @@ def cli_set_backend(self, args):
return None

def cli_convert(self, args):
prints(args)
printsd(args)
if args.all:
prints('in all')
printsd('in all')
# return NotImplemented
'`calibre-debug -r djvumaker convert_all`'
prints("Press Enter to copy-convert all PDFs to DJVU, or CTRL+C to abort...")
Expand All @@ -189,7 +183,7 @@ def cli_convert(self, args):
db.run_plugins_on_postimport(book_id, 'pdf')
continue
elif args.path is not None:
prints('path')
printsd('path')
return NotImplemented
if is_rasterbook(args.path):
'`calibre-debug -r djvumaker test.pdf` -> tempfile(test.djvu)'
Expand All @@ -211,7 +205,7 @@ def cli_convert(self, args):
os.system("djvused -e dump '%s'" % djvu)
os.system("djvused -v '%s'" % djvu)
elif args.id is not None:
prints('in id')
printsd('in id')
# return NotImplemented
'`calibre-debug -r djvumaker 123 #id(123).pdf` -> tempfile(id(123).djvu)'
self.postimport(args.id, 'pdf') # bookid and book_format, can go really wrong
Expand Down Expand Up @@ -334,14 +328,14 @@ def is_rasterbook(path):
Ascertain this by checking whether there are as many image objects in the PDF
as there are pages +/- 5 (google books and other scanners add pure-text preambles to their pdfs)
'''
prints('enter is_rasterbook: {}'.format(path))
printsd('enter is_rasterbook: {}'.format(path))
podofo = get_podofo()
pdf = podofo.PDFDoc()
prints('opens file')
printsd('opens file')
pdf.open(path)
prints('\n starts counting pages')
printsd('\n starts counting pages')
pages = pdf.page_count()
prints('\n number of pages: {}'.format(pages))
printsd('\n number of pages: {}'.format(pages))
try:
# without try statment, a lot of PDFs causes podofo.Error:
# Error: A NULL handle was passed, but initialized data was expected.
Expand All @@ -362,7 +356,7 @@ def is_rasterbook(path):
# TODO: WARN or ASK user what to do, image count is unknown
return True
else:
prints("%s: pages(%s) : images(%s) > %s" % (PLUGINNAME, pages, images, path))
prints("pages(%s) : images(%s) > %s" % (pages, images, path))
if pages > 0:
return abs(pages - images) <= 5
return False
Expand Down
97 changes: 61 additions & 36 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import urlparse
import os.path
import subprocess

from calibre.constants import (isosx, iswindows, islinux, isbsd)

def create_cli_parser(self_DJVUmaker, PLUGINNAME, PLUGINVER_DOT):
parser = argparse.ArgumentParser(prog="calibre-debug -r {} -- ".format(PLUGINNAME))
Expand Down Expand Up @@ -37,67 +39,90 @@ def create_cli_parser(self_DJVUmaker, PLUGINNAME, PLUGINVER_DOT):

parser_install_deps = subparsers.add_parser('install_deps',
help='(depreciated) alias for `{}backend install djvudigital`'.format(parser.prog))
parser_install_deps.set_defaults(func=self_DJVUmaker.cli_backend, command='install', backend='djvudigital')
parser_install_deps.set_defaults(func=self_DJVUmaker.cli_backend, command='install',
backend='djvudigital')
parser_convert_all = subparsers.add_parser('convert_all',
help='(depreciated) alias for `{}convert --all`'.format(parser.prog))
parser_convert_all.set_defaults(func=self_DJVUmaker.cli_convert, all=True)
return parser

def install_pdf2djvu(log=print):
try:
try:
# on python 3.3 exist os.which
sbp_out = subprocess.check_output(['pdf2djvu', '--version'],
stderr= subprocess.STDOUT)
curr_version = sbp_out.splitlines()[0].split()[1]
log('Version {} of pdf2djvu is found locally.'.format(curr_version))
except OSError:
curr_version = None
log('pdf2djvu is not found locally.')
except:
log('Output:' + sbp_out)
raise

def get_url_basename(url):
return os.path.basename(urlparse.urlsplit(url).path)

github_latest_url = r'https://github.com/jwilk/pdf2djvu/releases/latest'
github_page = urllib2.urlopen(github_latest_url)
new_version = get_url_basename(github_page.geturl())
# new_version = '0.9.5'
# github_latest_url = r'https://github.com/jwilk/pdf2djvu/releases/latest'
# github_page = urllib2.urlopen(github_latest_url)
# new_version = get_url_basename(github_page.geturl())
new_version = '0.9.5'
log('Version {} of pdf2djvu is available on program\'s GitHub page.'.format(new_version))

def version_str_to_intlist(verstr):
return [int(x) for x in verstr.split('.')]
new_ver_intlist = version_str_to_intlist(new_version)

if curr_version is None:
log('Do you want to dowload current version of pdf2djvu?')
if raw_input('y/n') != 'y':
raise Exception('bad input')
fpath = download_pdf2djvu(new_version, log)
unpack_pdf2djvu(fpath, log)

curr_ver_intlist = version_str_to_intlist(curr_version)
new_ver_intlist = version_str_to_intlist(new_version)
if new_ver_intlist == curr_ver_intlist:
log('You have already current version of pdf2djvu.')
elif new_ver_intlist > curr_ver_intlist:
log('Do you want to download newer version of pdf2djvu?')
if raw_input('y/n') != 'y':
raise Exception('bad input')

def gen_zip_url(code):
return r'https://github.com/jwilk/pdf2djvu/releases/download/{}/pdf2djvu-win32-{}.zip'.format(code, code)
def gen_tar_url(code):
return r'https://github.com/jwilk/pdf2djvu/releases/download/{}/pdf2djvu-{}.tar.xz'.format(code, code)
if iswindows:
fallback_arch_url = gen_zip_url('0.9.5')
arch_url = gen_zip_url(new_version)
else:
fallback_arch_url = gen_tar_url('0.9.5')
arch_url = gen_tar_url(new_version)

fpath, msg = urllib.urlretrieve(arch_url, os.path.join('plugins',
get_url_basename(arch_url)))
if msg['Status'].split()[0] not in ['200', '302']:
fpath, msg_fallback = urllib.urlretrieve(fallback_arch_url, os.path.join('plugins',
get_url_basename(fallback_arch_url)))
if msg_fallback.split()[0] not in ['200', '302']:
raise Exception('Cannot download pdf2djvu')

if iswindows:
from zipfile import ZipFile
with ZipFile(fpath, 'r') as myzip:
myzip.extractall()
else:
raise Exception('Python 2.7 Standard Library cannot unpack tar.xz archive, do this manualy')
fpath = download_pdf2djvu(new_version, log)
unpack_pdf2djvu(fpath, log)

else: #new_ver_intlist < curr_ver_intlist
raise Exception("Newer version than current pdf2djvu found.")

def get_url_basename(url):
return os.path.basename(urlparse.urlsplit(url).path)

def download_pdf2djvu(new_version, log):
def gen_zip_url(code):
return r'https://github.com/jwilk/pdf2djvu/releases/download/{}/pdf2djvu-win32-{}.zip'.format(code, code)
def gen_tar_url(code):
return r'https://github.com/jwilk/pdf2djvu/releases/download/{}/pdf2djvu-{}.tar.xz'.format(code, code)

fallback_version = '0.9.5'
if iswindows:
fallback_arch_url = gen_zip_url(fallback_version)
arch_url = gen_zip_url(new_version)
else:
fallback_arch_url = gen_tar_url(fallback_version)
arch_url = gen_tar_url(new_version)

log('Downloading current version of pdf2djvu...')
fpath, msg = urllib.urlretrieve(arch_url, os.path.join('plugins', get_url_basename(arch_url)))
if msg['Status'].split()[0] not in ['200', '302']:
log('Cannot download current version {} from GitHub.'.format(new_version))
if new_version != fallback_version:
log('Trying download version {}...'.format(fallback_version))
fpath, msg_fallback = urllib.urlretrieve(fallback_arch_url, os.path.join('plugins',
get_url_basename(fallback_arch_url)))
if msg_fallback.split()[0] not in ['200', '302']:
raise Exception('Cannot download pdf2djvu.')
return fpath

def unpack_pdf2djvu(fpath, log):
if iswindows:
from zipfile import ZipFile
with ZipFile(fpath, 'r') as myzip:
myzip.extractall()
else:
raise Exception('Python 2.7 Standard Library cannot unpack tar.xz archive, do this manualy')

0 comments on commit 5627b27

Please sign in to comment.