Skip to content

Commit

Permalink
Installation scripts for pdf2djvu
Browse files Browse the repository at this point in the history
  • Loading branch information
pirtim committed Mar 27, 2017
1 parent 5627b27 commit 5c0b026
Show file tree
Hide file tree
Showing 2 changed files with 310 additions and 83 deletions.
77 changes: 52 additions & 25 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
sys.stdout.write(PLUGINVER_DOT) #Makefile needs this to do releases
sys.exit()

import errno, os, sys, traceback, argparse, subprocess
import errno, os, sys, traceback, argparse, subprocess, collections
from functools import partial, wraps

from calibre import force_unicode, prints
Expand All @@ -27,6 +27,7 @@
from calibre.utils.config import JSONConfig
from calibre.utils.podofo import get_podofo
from calibre.utils.ipc.simple_worker import fork_job as worker_fork_job, WorkerError
from calibre_plugins.djvumaker.utils import create_backend_link, create_cli_parser, install_pdf2djvu, discover_backend

# if iswindows and hasattr(sys, 'frozen'):
# # CREATE_NO_WINDOW=0x08 so that no ugly console is popped up
Expand All @@ -38,7 +39,14 @@
#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

DEBUG = True # set True for debugging
def empty_function(*args, **kwargs):
pass
if DEBUG:
printsd = partial(prints, '{}:'.format('DEBUG')) # for DEBUG msg
else:
printsd = empty_function

# -- Calibre Plugin class --
class DJVUmaker(FileTypePlugin, InterfaceActionBase): #multiple inheritance for gui hooks!
Expand All @@ -51,32 +59,42 @@ class DJVUmaker(FileTypePlugin, InterfaceActionBase): #multiple inheritance for
on_postimport = True # Run this plugin after books are addded to the database
minimum_calibre_version = (2, 22, 0) #needs the new db api w/id() bugfix, and podofo.image_count()
actual_plugin = 'calibre_plugins.djvumaker.gui:ConvertToDJVUAction' #InterfaceAction plugin location
REGISTERED_BACKENDS = {}
REGISTERED_BACKENDS = collections.OrderedDict()

def __init__(self, *args, **kwargs):
super(DJVUmaker, self).__init__(*args, **kwargs)
# REGISTERED_BACKENDS = ['pdf2djvu', 'djvudigital']
# Set default preferences
DEFAULT_STORE_VALUES = {}
DEFAULT_STORE_VALUES['plugin_version'] = PLUGINVER
for item in self.REGISTERED_BACKENDS:
DEFAULT_STORE_VALUES[item] = {'flags' : [], 'installed' : False}
DEFAULT_STORE_VALUES[item] = {
'flags' : [], 'installed' : False, 'version' : None}
if 'djvudigital' in self.REGISTERED_BACKENDS:
DEFAULT_STORE_VALUES['use_backend'] = 'djvudigital'
else:
raise Exception('No djvudigital backend.')


# JSONConfig is a dict-like object,
# if coresponding .json file has not a specific key, it's got from .defaults
self.plugin_prefs = JSONConfig(os.path.join('plugins', PLUGINNAME))
self.plugin_prefs.defaults = DEFAULT_STORE_VALUES

# make sure to create plugins/djvumaker.json
# self.plugin_prefs.values() deosn't use self.plugin_prefs.__getitem__()
# and returns real json not defaults
# self.plugin_prefs.values() doesn't use self.plugin_prefs.__getitem__()
# and returns real json, not defaults
if not self.plugin_prefs.values():
for key, val in DEFAULT_STORE_VALUES.iteritems():
self.plugin_prefs[key] = val

def run_backend(self, *args, **kwargs):
use_backend = self.plugin_prefs['use_backend']

# DEBUG DEL
use_backend = 'pdf2djvu'
prints(subprocess.check_output(['pwd']))
kwargs['preferences'] = self.plugin_prefs

return self.REGISTERED_BACKENDS[use_backend](*args, **kwargs)

@classmethod
Expand All @@ -95,14 +113,18 @@ def cli_main(self, args):
'''Handles plugin cli interface'''
args = args[1:] # args[0] = PLUGINNAME
printsd('cli_main enter: args: ', args) # DEBUG
from calibre_plugins.djvumaker.utils import create_cli_parser
parser = create_cli_parser(self, PLUGINNAME, PLUGINVER_DOT)
# from calibre_plugins.djvumaker.utils import create_cli_parser
parser = create_cli_parser(self, PLUGINNAME, PLUGINVER_DOT,
self.REGISTERED_BACKENDS.keys())
if len(args) == 0:
parser.print_help()
return sys.exit()
options = parser.parse_args(args)
options.func(options)

def cli_test(self, args):
prints(subprocess.check_output(['pwd']))

def cli_backend(self, args):
printsd('cli_backend enter: plugin_prefs:', self.plugin_prefs)
if args.command == 'install':
Expand Down Expand Up @@ -130,7 +152,8 @@ def cli_install_backend(self, args):
raise Exception("Homebrew required."
"Please visit https://github.com/Homebrew/homebrew")
if raw_input("Install DjView.app? (y/n): ").lower() == 'y':
os.system("brew install caskroom/cask/brew-cask; brew cask install djview")
os.system("brew install caskroom/cask/brew-cask;"
" brew cask install djview")
else:
sys.exit()
#need a cask for the caminova finder/safari plugin too
Expand All @@ -143,15 +166,19 @@ def cli_install_backend(self, args):
# TODO: inherit from JSONConfig and make better implementation for defaults
elif args.backend == 'pdf2djvu':
# raise NotImplementedError
from calibre_plugins.djvumaker.utils import install_pdf2djvu
result = install_pdf2djvu(log=prints)
# from calibre_plugins.djvumaker.utils import install_pdf2djvu
success, version = install_pdf2djvu(PLUGINNAME, self.plugin_prefs, log=prints)
# path?
# TODO: give flag where to installed_backend
# TODO: ask if add to path?
# TODO: should use github api v3
self.plugin_prefs['pdf2djvu']['installed'] = True
self.plugin_prefs.commit() # always use commit if uses nested dict
prints('Installation of pdf2djvu was succesfull or unrequired.')
if success:
self.plugin_prefs['pdf2djvu']['installed'] = True
self.plugin_prefs['pdf2djvu']['version'] = version
self.plugin_prefs.commit() # always use commit if uses nested dict
prints('Installation of pdf2djvu was succesfull or unrequired.')
else:
prints('Installation of pdf2djvu was not succesfull.')
else:
raise Exception('Backend not recognized.')

Expand All @@ -162,6 +189,7 @@ def cli_set_backend(self, args):

if args.backend in self.REGISTERED_BACKENDS:
self.plugin_prefs['use_backend'] = args.backend
prints('{} successfully set as current backend.'.format(args.backend))
else:
raise Exception('Backend not recognized.')
return None
Expand All @@ -188,15 +216,10 @@ def cli_convert(self, args):
if is_rasterbook(args.path):
'`calibre-debug -r djvumaker test.pdf` -> tempfile(test.djvu)'
djvu = self.run_backend(args.path)
# if self.plugin_prefs['Options']['use_backend'] == 'djvudigital':
# djvu = djvudigital(args.path)
# elif self.plugin_prefs['Options']['use_backend'] == 'pdf2djvu':
# djvu = pdf2djvu(args.path)
# TODO: make function from this, to start good backend, maybe second decorator?

if djvu:
prints("\n\nopening djvused in subshell, press Ctrl+D to exit and delete\
'%s'\n\n" % djvu)
prints(("\n\nopening djvused in subshell, press Ctrl+D to exit and"
"delete '%s'\n\n") % djvu)
#de-munge the tty
sys.stdin = sys.__stdin__
sys.stdout = sys.__stdout__
Expand Down Expand Up @@ -444,14 +467,18 @@ def raise_if_not_supported(srcdoc, supported_extensions):

@DJVUmaker.register_backend
@job_handler
def pdf2djvu(srcdoc, cmdflags, djvu):
def pdf2djvu(srcdoc, cmdflags, djvu, preferences):
'''pdf2djvu backend shell command generation'''
raise_if_not_supported(srcdoc, ['pdf'])
return ['pdf2djvu'] + ['-o', djvu.name, srcdoc] # command passed to subprocess
pdf2djvu_path, _, __, ___ = discover_backend('pdf2djvu', preferences, PLUGINNAME)
prints(pdf2djvu_path)
# command passed to subprocess
return [pdf2djvu_path, '-o', djvu.name, srcdoc]
# return [create_backend_link('pdf2djvu', backend_version), '-o', djvu.name, srcdoc]

@DJVUmaker.register_backend
@job_handler
def djvudigital(srcdoc, cmdflags, djvu):
def djvudigital(srcdoc, cmdflags, djvu, preferences):
'''djvudigital backend shell command generation'''
raise_if_not_supported(srcdoc, ['pdf', 'ps'])
return ['djvudigital'] + cmdflags + [srcdoc, djvu.name] # command passed to subprocess
Expand Down
Loading

0 comments on commit 5c0b026

Please sign in to comment.