code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from __future__ import absolute_import
__dependencies__ = []
__all__ = ['get_version', 'setup', 'release']
from setuptools import setup as _setup, find_packages, Command
from setuptools.command.sdist import sdist
from distutils import log
from distutils.errors import DistutilsSetupError
from datetime import date
from glob import glob
import os
import re
VERSION_PATTERN = re.compile(r"(?m)^__version__\s*=\s*['\"](.+)['\"]$")
DEPENDENCY_PATTERN = re.compile(
r"(?m)__dependencies__\s*=\s*\[((['\"].+['\"]\s*(,\s*)?)+)\]")
base_module = __name__.rsplit('.', 1)[0]
def get_version(module_name_or_file=None):
"""Return the current version as defined by the given module/file."""
if module_name_or_file is None:
parts = base_module.split('.')
module_name_or_file = parts[0] if len(parts) > 1 else \
find_packages(exclude=['test', 'test.*'])[0]
if os.path.isdir(module_name_or_file):
module_name_or_file = os.path.join(module_name_or_file, '__init__.py')
with open(module_name_or_file, 'r') as f:
match = VERSION_PATTERN.search(f.read())
return match.group(1)
def get_dependencies(module):
basedir = os.path.dirname(__file__)
fn = os.path.join(basedir, module + '.py')
if os.path.isfile(fn):
with open(fn, 'r') as f:
match = DEPENDENCY_PATTERN.search(f.read())
if match:
return [s.strip().strip('"\'')
for s in match.group(1).split(',')]
return []
def get_package(module):
return base_module + '.' + module
def setup(**kwargs):
# TODO: Find a better way to pass this to a command.
os.environ['setup_long_name'] = kwargs.pop('long_name', kwargs.get('name'))
if 'version' not in kwargs:
kwargs['version'] = get_version()
packages = kwargs.setdefault(
'packages',
find_packages(exclude=['test', 'test.*', base_module + '.*']))
packages.append(__name__)
install_requires = kwargs.setdefault('install_requires', [])
for yc_module in kwargs.pop('yc_requires', []):
packages.append(get_package(yc_module))
for dep in get_dependencies(yc_module):
if dep not in install_requires:
install_requires.append(dep)
cmdclass = kwargs.setdefault('cmdclass', {})
cmdclass.setdefault('release', release)
cmdclass.setdefault('build_man', build_man)
cmdclass.setdefault('sdist', custom_sdist)
return _setup(**kwargs)
class custom_sdist(sdist):
def run(self):
self.run_command('build_man')
# Run if available:
if 'qt_resources' in self.distribution.cmdclass:
self.run_command('qt_resources')
sdist.run(self)
class build_man(Command):
description = "create man pages from asciidoc source"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
self.cwd = os.getcwd()
self.fullname = self.distribution.get_fullname()
self.name = self.distribution.get_name()
self.version = self.distribution.get_version()
def run(self):
if os.getcwd() != self.cwd:
raise DistutilsSetupError("Must be in package root!")
for fname in glob(os.path.join('man', '*.adoc')):
self.announce("Converting: " + fname, log.INFO)
self.execute(os.system,
('a2x -d manpage -f manpage "%s"' % fname,))
class release(Command):
description = "create and release a new version"
user_options = [
('keyid', None, "GPG key to sign with"),
('skip-tests', None, "skip running the tests"),
('pypi', None, "publish to pypi"),
]
boolean_options = ['skip-tests', 'pypi']
def initialize_options(self):
self.keyid = None
self.skip_tests = 0
self.pypi = 0
def finalize_options(self):
self.cwd = os.getcwd()
self.fullname = self.distribution.get_fullname()
self.name = self.distribution.get_name()
self.version = self.distribution.get_version()
def _verify_version(self):
with open('NEWS', 'r') as news_file:
line = news_file.readline()
now = date.today().strftime('%Y-%m-%d')
if not re.search(r'Version %s \(released %s\)' % (self.version, now),
line):
raise DistutilsSetupError("Incorrect date/version in NEWS!")
def _verify_tag(self):
if os.system('git tag | grep -q "^%s\$"' % self.fullname) == 0:
raise DistutilsSetupError(
"Tag '%s' already exists!" % self.fullname)
def _verify_not_dirty(self):
if os.system('git diff --shortstat | grep -q "."') == 0:
raise DistutilsSetupError("Git has uncommitted changes!")
def _sign(self):
if os.path.isfile('dist/%s.tar.gz.asc' % self.fullname):
# Signature exists from upload, re-use it:
sign_opts = ['--output dist/%s.tar.gz.sig' % self.fullname,
'--dearmor dist/%s.tar.gz.asc' % self.fullname]
else:
# No signature, create it:
sign_opts = ['--detach-sign', 'dist/%s.tar.gz' % self.fullname]
if self.keyid:
sign_opts.insert(1, '--default-key ' + self.keyid)
self.execute(os.system, ('gpg ' + (' '.join(sign_opts)),))
if os.system('gpg --verify dist/%s.tar.gz.sig' % self.fullname) != 0:
raise DistutilsSetupError("Error verifying signature!")
def _tag(self):
tag_opts = ['-s', '-m ' + self.fullname, self.fullname]
if self.keyid:
tag_opts[0] = '-u ' + self.keyid
self.execute(os.system, ('git tag ' + (' '.join(tag_opts)),))
def run(self):
if os.getcwd() != self.cwd:
raise DistutilsSetupError("Must be in package root!")
self._verify_version()
self._verify_tag()
self._verify_not_dirty()
self.run_command('check')
self.execute(os.system, ('git2cl > ChangeLog',))
self.run_command('sdist')
if not self.skip_tests:
try:
self.run_command('test')
except SystemExit as e:
if e.code != 0:
raise DistutilsSetupError("There were test failures!")
if self.pypi:
cmd_obj = self.distribution.get_command_obj('upload')
cmd_obj.sign = True
if self.keyid:
cmd_obj.identity = self.keyid
self.run_command('upload')
self._sign()
self._tag()
self.announce("Release complete! Don't forget to:", log.INFO)
self.announce("")
self.announce(" git push && git push --tags", log.INFO)
self.announce("") | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/yubicommon/setup/__init__.py | __init__.py |
from __future__ import absolute_import
import os.path
import re
import sys
import glob
import platform
import ctypes
import ctypes.util
def _environ_path(name):
if name in os.environ:
return os.environ[name].split(":")
else:
return []
class LibraryLoader(object):
def __init__(self):
self.other_dirs = []
def load_library(self, libname, version=None):
"""Given the name of a library, load it."""
paths = self.getpaths(libname)
for path in paths:
if os.path.exists(path):
return self.load(path)
raise ImportError("%s not found." % libname)
def load(self, path):
"""Given a path to a library, load it."""
try:
# Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
# of the default RTLD_LOCAL. Without this, you end up with
# libraries not being loadable, resulting in "Symbol not found"
# errors
if sys.platform == 'darwin':
return ctypes.CDLL(path, ctypes.RTLD_GLOBAL)
else:
return ctypes.cdll.LoadLibrary(path)
except OSError as e:
raise ImportError(e)
def getpaths(self, libname):
"""Return a list of paths where the library might be found."""
if os.path.isabs(libname):
yield libname
else:
# FIXME / TODO return '.' and os.path.dirname(__file__)
for path in self.getplatformpaths(libname):
yield path
path = ctypes.util.find_library(libname)
if path:
yield path
def getplatformpaths(self, libname):
return []
# Darwin (Mac OS X)
class DarwinLibraryLoader(LibraryLoader):
name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
"%s.so", "%s.bundle", "%s"]
def getplatformpaths(self, libname):
if os.path.pathsep in libname:
names = [libname]
else:
names = [format % libname for format in self.name_formats]
for dir in self.getdirs(libname):
for name in names:
yield os.path.join(dir, name)
def getdirs(self, libname):
'''Implements the dylib search as specified in Apple documentation:
http://developer.apple.com/documentation/DeveloperTools/Conceptual/
DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
Before commencing the standard search, the method first checks
the bundle's ``Frameworks`` directory if the application is running
within a bundle (OS X .app).
'''
dyld_fallback_library_path = _environ_path(
"DYLD_FALLBACK_LIBRARY_PATH")
if not dyld_fallback_library_path:
dyld_fallback_library_path = [os.path.expanduser('~/lib'),
'/usr/local/lib', '/usr/lib']
dirs = []
if '/' in libname:
dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
else:
dirs.extend(_environ_path("LD_LIBRARY_PATH"))
dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
dirs.extend(self.other_dirs)
dirs.append(".")
dirs.append(os.path.dirname(__file__))
if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
dirs.append(os.path.join(
os.environ['RESOURCEPATH'],
'..',
'Frameworks'))
if hasattr(sys, 'frozen'):
dirs.append(sys._MEIPASS)
dirs.extend(dyld_fallback_library_path)
return dirs
# Posix
class PosixLibraryLoader(LibraryLoader):
_ld_so_cache = None
def load_library(self, libname, version=None):
try:
return self.load(ctypes.util.find_library(libname))
except ImportError:
return super(PosixLibraryLoader, self).load_library(
libname, version)
def _create_ld_so_cache(self):
# Recreate search path followed by ld.so. This is going to be
# slow to build, and incorrect (ld.so uses ld.so.cache, which may
# not be up-to-date). Used only as fallback for distros without
# /sbin/ldconfig.
#
# We assume the DT_RPATH and DT_RUNPATH binary sections are omitted.
directories = []
for name in ("LD_LIBRARY_PATH",
"SHLIB_PATH", # HPUX
"LIBPATH", # OS/2, AIX
"LIBRARY_PATH", # BE/OS
):
if name in os.environ:
directories.extend(os.environ[name].split(os.pathsep))
directories.extend(self.other_dirs)
directories.append(".")
directories.append(os.path.dirname(__file__))
try:
directories.extend([dir.strip()
for dir in open('/etc/ld.so.conf')])
except IOError:
pass
unix_lib_dirs_list = ['/lib', '/usr/lib', '/lib64', '/usr/lib64']
if sys.platform.startswith('linux'):
# Try and support multiarch work in Ubuntu
# https://wiki.ubuntu.com/MultiarchSpec
bitage = platform.architecture()[0]
if bitage.startswith('32'):
# Assume Intel/AMD x86 compat
unix_lib_dirs_list += [
'/lib/i386-linux-gnu', '/usr/lib/i386-linux-gnu']
elif bitage.startswith('64'):
# Assume Intel/AMD x86 compat
unix_lib_dirs_list += [
'/lib/x86_64-linux-gnu', '/usr/lib/x86_64-linux-gnu']
else:
# guess...
unix_lib_dirs_list += glob.glob('/lib/*linux-gnu')
directories.extend(unix_lib_dirs_list)
cache = {}
lib_re = re.compile(r'lib(.*)\.s[ol]')
ext_re = re.compile(r'\.s[ol]$')
for dir in directories:
try:
for path in glob.glob("%s/*.s[ol]*" % dir):
file = os.path.basename(path)
# Index by filename
if file not in cache:
cache[file] = path
# Index by library name
match = lib_re.match(file)
if match:
library = match.group(1)
if library not in cache:
cache[library] = path
except OSError:
pass
self._ld_so_cache = cache
def getplatformpaths(self, libname):
if self._ld_so_cache is None:
self._create_ld_so_cache()
result = self._ld_so_cache.get(libname)
if result:
yield result
path = ctypes.util.find_library(libname)
if path:
yield os.path.join("/lib", path)
# Windows
class _WindowsLibrary(object):
def __init__(self, path):
self.cdll = ctypes.cdll.LoadLibrary(path)
self.windll = ctypes.windll.LoadLibrary(path)
def __getattr__(self, name):
try:
return getattr(self.cdll, name)
except AttributeError:
try:
return getattr(self.windll, name)
except AttributeError:
raise
class WindowsLibraryLoader(LibraryLoader):
name_formats = ["%s.dll", "lib%s.dll", "%slib.dll"]
def load_library(self, libname, version=None):
try:
result = LibraryLoader.load_library(self, libname, version)
except ImportError:
result = None
if os.path.sep not in libname:
formats = self.name_formats[:]
if version:
formats.append("lib%%s-%s.dll" % version)
for name in formats:
try:
result = getattr(ctypes.cdll, name % libname)
if result:
break
except WindowsError:
result = None
if result is None:
try:
result = getattr(ctypes.cdll, libname)
except WindowsError:
result = None
if result is None:
raise ImportError("%s not found." % libname)
return result
def load(self, path):
return _WindowsLibrary(path)
def getplatformpaths(self, libname):
if os.path.sep not in libname:
for name in self.name_formats:
dll_in_current_dir = os.path.abspath(name % libname)
if os.path.exists(dll_in_current_dir):
yield dll_in_current_dir
path = ctypes.util.find_library(name % libname)
if path:
yield path
# Platform switching
# If your value of sys.platform does not appear in this dict, please contact
# the Ctypesgen maintainers.
loaderclass = {
"darwin": DarwinLibraryLoader,
"cygwin": WindowsLibraryLoader,
"win32": WindowsLibraryLoader
}
loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
def add_library_search_dirs(other_dirs):
loader.other_dirs = other_dirs
load_library = loader.load_library
del loaderclass | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/yubicommon/ctypes/libloader.py | libloader.py |
import os
from PySide import QtGui, QtCore
from functools import partial
from neoman import messages as m
from neoman.storage import settings
from neoman.exc import ModeSwitchError
from neoman.model.neo import YubiKeyNeo
from neoman.model.applet import Applet
from neoman.model.modes import MODE
from neoman.view.tabs import TabWidgetWithAbout
U2F_URL = "http://www.yubico.com/products/yubikey-hardware/yubikey-neo/" \
+ "yubikey-neo-u2f/"
def get_text(*args, **kwargs):
flags = (
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowSystemMenuHint
)
kwargs['flags'] = flags
return QtGui.QInputDialog.getText(*args, **kwargs)
class NeoPage(TabWidgetWithAbout):
_neo = QtCore.Signal(YubiKeyNeo)
applet = QtCore.Signal(Applet)
def __init__(self):
super(NeoPage, self).__init__()
self._tabs = []
self._supported = True
self._unsupported_tab = UnsupportedTab()
settings_tab = SettingsTab()
self._neo.connect(settings_tab.set_neo)
self.addTab(settings_tab, m.settings)
if QtCore.QCoreApplication.instance().devmode:
apps = AppsTab(self, 1)
self._neo.connect(apps.set_neo)
apps.applet.connect(self._set_applet)
self.addTab(apps, m.installed_apps)
def addTab(self, tab, title):
self._tabs.append((tab, title))
if self._supported:
super(NeoPage, self).addTab(tab, title)
@QtCore.Slot(YubiKeyNeo)
def setNeo(self, neo):
self._supported = neo and neo.supported
self.clear()
if self._supported:
for (tab, title) in self._tabs:
super(NeoPage, self).addTab(tab, title)
else:
super(NeoPage, self).addTab(self._unsupported_tab, m.settings)
self._neo.emit(neo)
@QtCore.Slot(Applet)
def _set_applet(self, applet):
self.applet.emit(applet)
class UnsupportedTab(QtGui.QWidget):
def __init__(self):
super(UnsupportedTab, self).__init__()
layout = QtGui.QVBoxLayout()
layout.addWidget(QtGui.QLabel(m.unsupported_device))
self.setLayout(layout)
class SettingsTab(QtGui.QWidget):
def __init__(self):
super(SettingsTab, self).__init__()
self._neo = None
self._name = QtGui.QLabel()
self._serial = QtGui.QLabel()
self._firmware = QtGui.QLabel()
self._u2f = QtGui.QLabel()
self._u2f.setOpenExternalLinks(True)
layout = QtGui.QVBoxLayout()
name_row = QtGui.QHBoxLayout()
name_row.addWidget(self._name)
self._name_btn = QtGui.QPushButton(m.change_name)
self._name_btn.clicked.connect(self.change_name)
name_row.addWidget(self._name_btn)
details_row = QtGui.QHBoxLayout()
details_row.addWidget(self._serial)
details_row.addWidget(self._firmware)
self._u2f_row = QtGui.QHBoxLayout()
self._u2f_row.addWidget(QtGui.QLabel())
self._u2f_row.addWidget(self._u2f)
layout.addLayout(name_row)
layout.addLayout(details_row)
layout.addLayout(self._u2f_row)
button = QtGui.QPushButton(m.manage_keys)
button.clicked.connect(self.manage_keys)
# TODO: Re-add when implemented:
# layout.addWidget(button)
self._mode_btn = QtGui.QPushButton(m.change_mode)
self._mode_btn.clicked.connect(self.change_mode)
layout.addWidget(self._mode_btn)
self._mode_note = QtGui.QLabel(m.note_1 % m.mode_note)
self._mode_note.setWordWrap(True)
layout.addWidget(self._mode_note)
layout.addStretch()
self.setLayout(layout)
@QtCore.Slot(YubiKeyNeo)
def set_neo(self, neo):
self._neo = neo
if not neo:
return
self._name_btn.setDisabled(neo.serial is None)
self._name.setText(m.name_1 % neo.name)
self._serial.setText(m.serial_1 % neo.serial)
show_firmware = neo.version != (0, 0, 0)
self._u2f_row.setDirection(
QtGui.QBoxLayout.LeftToRight if show_firmware else
QtGui.QBoxLayout.RightToLeft)
self._firmware.setVisible(show_firmware)
self._firmware.setText(m.firmware_1 % '.'.join(map(str, neo.version)))
if neo.allowed_modes[2]:
self._u2f.setText(m.u2f_1 % m.u2f_supported)
else:
self._u2f.setText(m.u2f_1 % m.u2f_not_supported_1 % U2F_URL)
self._mode_btn.setText(m.change_mode_1 % MODE.name_for_mode(neo.mode))
self._mode_note.setVisible(neo.version < (4, 1, 0))
def change_name(self):
name, ok = get_text(self, m.name, m.change_name_desc,
text=self._neo.name)
if ok:
self._neo.name = name
self._name.setText(m.name_1 % name)
def manage_keys(self):
print m.manage_keys
def change_mode(self):
mode = ModeDialog.change_mode(self._neo, self)
if mode is not None:
try:
self._neo.set_mode(mode)
except ModeSwitchError:
QtGui.QMessageBox.critical(self, m.mode_error,
m.mode_error_desc)
return
self._mode_btn.setText(m.change_mode_1 % MODE.name_for_mode(mode))
remove_dialog = QtGui.QMessageBox(self)
remove_dialog.setWindowTitle(m.change_mode)
remove_dialog.setIcon(QtGui.QMessageBox.Information)
remove_dialog.setText(m.remove_device)
remove_dialog.setStandardButtons(QtGui.QMessageBox.NoButton)
self._neo.removed.connect(remove_dialog.accept)
remove_dialog.exec_()
class ModeDialog(QtGui.QDialog):
def __init__(self, neo, parent=None):
super(ModeDialog, self).__init__(parent)
self.setWindowFlags(self.windowFlags()
^ QtCore.Qt.WindowContextHelpButtonHint)
layout = QtGui.QVBoxLayout()
layout.addWidget(QtGui.QLabel(m.change_mode_desc))
boxes = QtGui.QHBoxLayout()
self._otp = QtGui.QCheckBox(m.otp)
self._otp.clicked.connect(self._state_changed)
boxes.addWidget(self._otp)
self._ccid = QtGui.QCheckBox(m.ccid)
self._ccid.clicked.connect(self._state_changed)
boxes.addWidget(self._ccid)
self._u2f = QtGui.QCheckBox(m.u2f)
self._u2f.clicked.connect(self._state_changed)
boxes.addWidget(self._u2f)
layout.addLayout(boxes)
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
self._ok = buttons.button(QtGui.QDialogButtonBox.Ok)
layout.addWidget(buttons)
self.setWindowTitle(m.change_mode)
self.setLayout(layout)
allowed = neo.allowed_modes
self._otp.setEnabled(allowed[0])
self._otp.setVisible(allowed[0])
self._ccid.setEnabled(allowed[1])
self._ccid.setVisible(allowed[1])
self._u2f.setEnabled(allowed[2])
self._u2f.setVisible(allowed[2])
self.mode = neo.mode
def _state_changed(self):
self._ok.setDisabled(not any(self.flags))
@property
def flags(self):
return self._otp.isChecked(), self._ccid.isChecked(), \
self._u2f.isChecked()
@property
def mode(self):
return MODE.mode_for_flags(*self.flags)
@mode.setter
def mode(self, value):
otp, ccid, u2f, touch_eject = MODE.flags_for_mode(value)
self._otp.setChecked(otp and self._otp.isEnabled())
self._ccid.setChecked(ccid and self._ccid.isEnabled())
self._u2f.setChecked(u2f and self._u2f.isEnabled())
@classmethod
def change_mode(cls, neo, parent=None):
dialog = cls(neo, parent)
if dialog.exec_():
mode = dialog.mode
legacy = neo.version < (3, 3, 0)
if legacy and mode == 2: # Always set 82 instead of 2
mode = 0x82
return mode
else:
return None
class AppsTab(QtGui.QWidget):
applet = QtCore.Signal(Applet)
def __init__(self, parent, index):
super(AppsTab, self).__init__()
self.parent = parent
self.index = index
layout = QtGui.QVBoxLayout()
self._apps = []
self._apps_list = QtGui.QListView()
self._apps_list.setModel(QtGui.QStringListModel([]))
self._apps_list.setEditTriggers(QtGui.QListView.NoEditTriggers)
self._apps_list.doubleClicked.connect(self.open_app)
layout.addWidget(self._apps_list)
self._install_cap_btn = QtGui.QPushButton(m.install_cap)
self._install_cap_btn.clicked.connect(self.install_cap)
layout.addWidget(self._install_cap_btn)
layout.addStretch()
self.setLayout(layout)
parent.currentChanged.connect(self.tab_changed)
def install_cap(self):
path = settings.value('filepicker/path', None)
(cap, _) = QtGui.QFileDialog.getOpenFileName(self, m.select_cap,
path, "*.cap")
if not cap:
return
settings.setValue('filepicker/path', os.path.dirname(cap))
worker = QtCore.QCoreApplication.instance().worker
self._cap = os.path.basename(cap)
worker.post(m.installing, partial(self._neo.install_app, cap),
self.install_done)
@QtCore.Slot(object)
def install_done(self, status):
if status:
print status
QtGui.QMessageBox.warning(self, m.error_installing,
m.error_installing_1 % self._cap)
self.set_neo(self._neo)
def open_app(self, index):
readable = index.data()
aid = readable[readable.rindex('(') + 1:readable.rindex(')')]
appletmanager = QtCore.QCoreApplication.instance().appletmanager
self.applet.emit(appletmanager.get_applet(aid))
def tab_changed(self, index):
if index != self.index:
return
try:
while self._neo.locked:
try:
self._neo.unlock()
except Exception as e:
del self._neo.key
print e
pw, ok = get_text(self, m.key_required, m.key_required_desc)
if not ok:
self.parent.setCurrentIndex(0)
return
self._neo.key = pw
appletmanager = QtCore.QCoreApplication.instance().appletmanager
self._apps = filter(None, map(appletmanager.get_applet,
self._neo.list_apps()))
self._apps_list.model().setStringList(
map(lambda app: "%s (%s)" % (app.name, app.aid), self._apps))
except AttributeError:
pass
@QtCore.Slot(YubiKeyNeo)
def set_neo(self, neo):
self._neo = neo
if not neo or not neo.has_ccid:
self.parent.setTabEnabled(self.index, False)
self.parent.setTabToolTip(self.index, m.requires_ccid)
return
self.parent.setTabEnabled(self.index, True)
self.parent.setTabToolTip(self.index, None)
if neo.locked:
try:
neo.unlock()
except:
return
appletmanager = QtCore.QCoreApplication.instance().appletmanager
self._apps = filter(None, map(appletmanager.get_applet,
neo.list_apps()))
self._apps_list.model().setStringList(
map(lambda app: "%s (%s)" % (app.name, app.aid), self._apps)) | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/view/neo.py | neo.py |
from PySide import QtGui
from PySide import QtCore
from neoman.model.neo import YubiKeyNeo
from neoman.model.applet import Applet
from neoman.view.nav import NavTree
from neoman.view.welcome import WelcomePage
from neoman.view.neo import NeoPage
from neoman.view.applet import AppletPage
from neoman.storage import settings
from PySide.QtGui import QSizePolicy
class CentralWidget(QtGui.QWidget):
def __init__(self):
super(CentralWidget, self).__init__()
self.build_ui()
self.resize(settings.value('window/size', QtCore.QSize(0, 0)))
def build_ui(self):
layout = QtGui.QHBoxLayout(self)
layout.addWidget(self.build_nav())
layout.addWidget(self.build_main())
self._nav.subpage.connect(self._main.setContent)
self._main.setContent(self._nav.current)
self._main.current.connect(self._nav.setCurrent)
def build_nav(self):
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._nav = NavTree()
layout.addWidget(self._nav)
widget = QtGui.QWidget()
widget.setLayout(layout)
widget.setMaximumWidth(200)
widget.setSizePolicy(QSizePolicy.Fixed,
QSizePolicy.Expanding)
return widget
def build_main(self):
self._main = ContentWidget()
return self._main
def closeEvent(self, event):
settings.setValue('window/size', self.size())
event.accept()
class ContentWidget(QtGui.QStackedWidget):
current = QtCore.Signal(object)
_neo = QtCore.Signal(YubiKeyNeo)
_applet = QtCore.Signal(Applet)
def __init__(self):
super(ContentWidget, self).__init__()
self._content = None
self._start_page = WelcomePage()
self.addWidget(self._start_page)
self._neo_page = NeoPage()
self._neo_page.applet.connect(self.setContent)
self._neo.connect(self._neo_page.setNeo)
self.addWidget(self._neo_page)
self._app_page = AppletPage()
self._app_page.applet_status.connect(self.setContent)
self._neo.connect(self._app_page.setNeo)
self._applet.connect(self._app_page.setApplet)
self.addWidget(self._app_page)
self.setMinimumSize(420, 240)
self.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
@QtCore.Slot(YubiKeyNeo)
@QtCore.Slot(Applet)
def setContent(self, content):
self._content = content
if content is None:
self._neo.emit(None)
self._applet.emit(None)
self.setCurrentWidget(self._start_page)
elif isinstance(content, YubiKeyNeo):
self._neo.emit(content)
self.setCurrentWidget(self._neo_page)
elif isinstance(content, Applet):
self._applet.emit(content)
self.setCurrentWidget(self._app_page)
self.current.emit(content) | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/view/main.py | main.py |
from PySide import QtGui, QtCore
from neoman.model.applet import Applet
from neoman.model.neo import YubiKeyNeo
from neoman.storage import capstore
from neoman.view.tabs import TabWidgetWithAbout
from neoman import messages as m
from functools import partial
class AppletPage(TabWidgetWithAbout):
applet_status = QtCore.Signal(Applet)
_applet = QtCore.Signal(Applet)
_neo = QtCore.Signal(YubiKeyNeo)
def __init__(self):
super(AppletPage, self).__init__()
overview = OverviewTab()
overview.install_status.connect(self._install_status_changed)
self._applet.connect(overview.set_applet)
self._neo.connect(overview.set_neo)
self.addTab(overview, m.overview)
def _install_status_changed(self, applet, installed):
self.applet_status.emit(applet)
@QtCore.Slot(Applet)
def setApplet(self, applet):
self._applet.emit(applet)
@QtCore.Slot(YubiKeyNeo)
def setNeo(self, neo):
self._neo.emit(neo)
class OverviewTab(QtGui.QWidget):
install_status = QtCore.Signal(Applet, bool)
def __init__(self):
super(OverviewTab, self).__init__()
self._applet = None
self._neo = None
self._name = QtGui.QLabel()
self._description = QtGui.QLabel()
self._status = QtGui.QLabel()
self._aid = QtGui.QLabel()
self._latest_version = QtGui.QLabel()
available = QtCore.QCoreApplication.instance().available_neos
available.changed.connect(self.data_changed)
self._neo_selector = QtGui.QComboBox()
self._neo_selector.activated.connect(self.neo_selected)
for neo in available.get():
self._neo_selector.addItem(neo.name, neo)
self._install_button = QtGui.QPushButton()
self._install_button.clicked.connect(self.install_button_click)
header = QtGui.QHBoxLayout()
col_1 = QtGui.QVBoxLayout()
col_2 = QtGui.QVBoxLayout()
col_1.addWidget(self._name)
col_1.addWidget(self._status)
#col_1.addWidget(self._aid)
col_2.addWidget(self._neo_selector)
if QtCore.QCoreApplication.instance().devmode:
col_1.addWidget(self._latest_version)
col_2.addWidget(self._install_button)
header.addLayout(col_1)
header.addLayout(col_2)
layout = QtGui.QVBoxLayout()
layout.addLayout(header)
separator = QtGui.QFrame()
separator.setFrameStyle(QtGui.QFrame.HLine | QtGui.QFrame.Sunken)
layout.addWidget(separator)
layout.addWidget(self._description)
layout.addStretch()
self.setLayout(layout)
def install_button_click(self):
installed = self._neo and any(
[x.startswith(self._applet.aid) for x in self._neo.list_apps()])
worker = QtCore.QCoreApplication.instance().worker
if installed: # Uninstall
if QtGui.QMessageBox.Ok != QtGui.QMessageBox.warning(
self, m.delete_app_confirm, m.delete_app_desc,
QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel):
return
work = partial(self._neo.delete_app, self._applet.aid)
worker.post(m.deleting_1 % self._applet.name, work,
self._cb_uninstall)
elif self._applet.is_downloaded: # Install
work = partial(self._neo.install_app, self._applet.cap_file)
worker.post(m.installing_1 % self._applet.name, work,
self._cb_install)
else: # Download and install
worker.download(self._applet.cap_url, self._cb_download)
@QtCore.Slot(object)
def _cb_install(self, result):
if result:
msg = m.error_installing_1 % self._applet.name
msg += '\n%s' % result
QtGui.QMessageBox.warning(self, m.error_installing, msg)
self.install_status.emit(self._applet, True)
self.neo_or_applet_changed(self._neo, self._applet)
@QtCore.Slot(object)
def _cb_uninstall(self, result):
if result:
msg = m.error_uninstalling_1 % self._applet.name
msg += '\n%s' % result
QtGui.QMessageBox.warning(self, m.error_uninstalling, msg)
self.install_status.emit(self._applet, False)
self.neo_or_applet_changed(self._neo, self._applet)
@QtCore.Slot(object)
def _cb_download(self, result):
if isinstance(result, QtCore.QByteArray):
capstore.store_data(self._applet.aid, self._applet.latest_version,
result, self._applet.cap_sha1)
self.install_button_click() # Now install
else:
msg = m.error_downloading_1 % self._applet.name
msg += '\n%s' % result
QtGui.QMessageBox.warning(self, m.error_downloading, msg)
@QtCore.Slot(Applet)
def set_applet(self, applet):
if applet:
self._applet = applet
self._name.setText(m.name_1 % applet.name)
self._aid.setText(m.aid_1 % applet.aid)
self._latest_version.setText(
m.latest_version_1 % (applet.latest_version or m.unknown))
self._description.setText(applet.description)
self.neo_or_applet_changed(self._neo, applet)
@QtCore.Slot(YubiKeyNeo)
def set_neo(self, neo):
if neo and neo.has_ccid:
self._neo = neo
self._neo_selector.setCurrentIndex(
self._neo_selector.findData(neo))
self.neo_or_applet_changed(neo, self._applet)
def neo_or_applet_changed(self, neo, applet):
if not applet:
return
installed, version = applet.get_status(neo) if neo else (False, None)
if installed:
if version:
self._status.setText(m.status_1 % (m.installed_1 % version))
else:
self._status.setText(m.status_1 % m.installed)
else:
self._status.setText(m.status_1 % m.not_installed)
if installed:
enabled = applet.allow_uninstall
elif applet.is_downloaded:
enabled = bool(neo)
else:
enabled = bool(neo and applet.cap_url)
self._install_button.setText(m.uninstall if installed else m.install)
self._install_button.setEnabled(enabled)
if neo and self._neo_selector.currentText() != neo.name:
self._neo_selector.setItemText(self._neo_selector.currentIndex(),
neo.name)
@QtCore.Slot(int)
def neo_selected(self, index):
self.set_neo(self._neo_selector.itemData(index))
@QtCore.Slot(list)
def data_changed(self, new_neos):
self._neo_selector.clear()
new_neos = [neo for neo in new_neos if neo.has_ccid]
for neo in new_neos:
self._neo_selector.addItem(neo.name, neo)
if self._neo in new_neos:
self._neo_selector.setCurrentIndex(new_neos.index(self._neo))
else:
self._neo = None if not new_neos else new_neos[0]
self.neo_or_applet_changed(self._neo, self._applet)
# class SettingsTab
# - Manage app specific settings against NEOs which have it installed. | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/view/applet.py | applet.py |
from PySide import QtGui, QtCore
from neoman.model.neo import YubiKeyNeo
from neoman.model.applet import Applet
from neoman import messages as m
class NavTree(QtGui.QTreeView):
subpage = QtCore.Signal(object)
def __init__(self):
super(NavTree, self).__init__()
self.setHeaderHidden(True)
self.setModel(NavModel())
self.expandAll()
self.current = None
self.model().rowsInserted.connect(self._data_changed)
self._data_changed()
@QtCore.Slot(YubiKeyNeo)
@QtCore.Slot(Applet)
def setCurrent(self, current):
self.current = current
try:
if isinstance(current, YubiKeyNeo):
neo_index = self.model().neo_list.index(current)
self.setCurrentIndex(
self.model().index(
neo_index, 0, self.model().categories[m.devices]))
elif isinstance(current, Applet):
applet_index = self.model().applets.index(current)
self.setCurrentIndex(
self.model().index(
applet_index, 0, self.model().categories[m.apps]))
except:
self.clearSelection()
def setCurrentIndex(self, index):
super(NavTree, self).setCurrentIndex(index)
self.model().refresh_icons(index)
def currentChanged(self, current, previous):
if current.flags() & QtCore.Qt.ItemIsSelectable:
self.current = current.internalPointer()
self.subpage.emit(self.current)
elif not self.model().neo_list:
self.current = None
self.subpage.emit(None)
elif isinstance(self.current, YubiKeyNeo):
pass
else:
self.current = self.model().neo_list[0]
self.subpage.emit(self.current)
def _data_changed(self):
if not self.current and self.model().neo_list:
self.setCurrentIndex(
self.model().index(0, 0, self.model().categories[m.devices]))
elif isinstance(self.current, YubiKeyNeo) \
and self.current not in self.model().neo_list:
self.current = None
self.subpage.emit(None)
class NavModel(QtCore.QAbstractItemModel):
def __init__(self):
super(NavModel, self).__init__()
self.categories = {
m.devices: self.createIndex(0, 0, m.devices),
m.apps: self.createIndex(1, 0, m.apps)
}
self.refresh_icons()
self.applets = []
available = QtCore.QCoreApplication.instance().available_neos
available.changed.connect(self.data_changed)
self.neo_list = available.get()
self._update_applets()
def refresh_icons(self, index=None):
if index and index.isValid():
self._get_icon(index, True)
else:
self._icons = {m.devices: {}, m.apps: {}}
@QtCore.Slot(list)
def data_changed(self, new_neos):
parent = self.categories[m.devices]
self.beginRemoveRows(parent, 0, self.rowCount(parent) - 1)
self.neo_list = []
self.endRemoveRows()
self.beginInsertRows(parent, 0, len(new_neos) - 1)
self.neo_list = new_neos
self.endInsertRows()
self._update_applets()
self.refresh_icons()
def _update_applets(self):
parent = self.categories[m.apps]
self.beginRemoveRows(parent, 0, self.rowCount(parent) - 1)
self.applets = []
self.endRemoveRows()
new_applets = []
installed = {app for neo in self.neo_list for app in neo.list_apps()}
appletmanager = QtCore.QCoreApplication.instance().appletmanager
if QtCore.QCoreApplication.instance().devmode:
new_applets = appletmanager.get_applets()
else:
for applet in appletmanager.get_applets():
if any([aid.startswith(applet.aid) for aid in installed]):
new_applets.append(applet)
self.beginInsertRows(parent, 0, len(new_applets) - 1)
self.applets = new_applets
self.endInsertRows()
def index(self, row, column, parent=QtCore.QModelIndex()):
if not parent.isValid():
node = m.devices if row == 0 else m.apps
return self.categories[node]
category = parent.internalPointer()
if category == m.devices:
return self.createIndex(row, column, self.neo_list[row])
return self.createIndex(row, column, self.applets[row])
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
node = index.internalPointer()
if node in self.categories:
return QtCore.QModelIndex()
if isinstance(node, YubiKeyNeo):
return self.categories[m.devices]
return self.categories[m.apps]
def columnCount(self, parent=QtCore.QModelIndex()):
return 1
def rowCount(self, parent=QtCore.QModelIndex()):
if not parent.isValid():
return 2
node = parent.internalPointer()
if node in self.categories:
return len(self.neo_list if node == m.devices else self.applets)
return 0
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(index.internalPointer())
elif QtCore.QCoreApplication.instance().devmode and \
role == QtCore.Qt.DecorationRole:
return self._get_icon(index)
def _get_icon(self, index, force_refresh=False):
parent = index.parent()
if not parent.isValid():
return None
category = parent.internalPointer()
if force_refresh or index.row() not in self._icons[category]:
self._icons[category][index.row()] = self._build_icon(index)
return self._icons[category][index.row()]
def _build_icon(self, index):
item = index.internalPointer()
icon_template = ':/icon_%s.png'
if isinstance(item, Applet):
all_installed = bool(self.neo_list)
some_installed = False
for neo in self.neo_list:
if any((aid.startswith(item.aid) for aid in neo.list_apps())):
some_installed = True
else:
all_installed = False
if all_installed:
return QtGui.QPixmap(icon_template % 'installed')
elif some_installed:
return QtGui.QPixmap(icon_template % 'some_installed')
else:
return QtGui.QPixmap(icon_template % 'not_installed')
def flags(self, index):
node = index.internalPointer()
if node in self.categories:
return QtCore.Qt.ItemIsEnabled
return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/view/nav.py | nav.py |
from PySide import QtCore, QtGui
from neoman.device import open_all_devices, ResetStateException
from neoman.storage import settings
from functools import wraps
DEFAULT_KEY = "404142434445464748494a4b4c4d4e4f"
def with_mutex(mutex, func):
@wraps(func)
def inner(*args, **kwargs):
try:
mutex.lock()
return func(*args, **kwargs)
finally:
mutex.unlock()
return inner
class YubiKeyNeo(QtCore.QObject):
removed = QtCore.Signal()
def __init__(self, device):
super(YubiKeyNeo, self).__init__()
self._mutex = QtCore.QMutex(QtCore.QMutex.Recursive)
self._serial = device.serial
self._version = device.version
self._apps = None
self._group = self._serial if self._serial else "NOSERIAL"
self._set_device(device)
def _set_device(self, device):
if self.serial != device.serial or self.version != device.version:
print self.serial, self.version, device.serial, device.version
raise ValueError("New device must have same serial/version.")
self._dev = device
self._mode = device.mode
self._default_name = device.default_name
# self._apps = None
if device.has_ccid:
device.key = self.key.decode('hex')
def __setitem__(self, key, value):
settings.setValue('%s/%s' % (self._group, key), value)
def __delitem__(self, key):
settings.remove('%s/%s' % (self._group, key))
def __getitem__(self, key):
return self.get(key)
def __nonzero__(self):
return True
def __len__(self):
try:
settings.beginGroup('%s' % self._group)
return len(settings.allKeys())
finally:
settings.endGroup()
def __getattr__(self, name):
try:
self._mutex.lock()
if not self._dev:
raise AttributeError(name)
attr = getattr(self._dev, name)
if hasattr(attr, '__call__'):
attr = with_mutex(self._mutex, attr)
return attr
finally:
self._mutex.unlock()
def __delattr__(self, key):
del self[key]
def get(self, key, default=None):
return settings.value('%s/%s' % (self._group, key), default)
@property
def name(self):
return self.get('name', self._default_name)
@name.setter
def name(self, new_name):
self['name'] = new_name
@property
def key(self):
return self.get('key', DEFAULT_KEY)
@key.setter
def key(self, new_key):
self['key'] = new_key
try:
self._mutex.lock()
self._dev.key = new_key.decode('hex')
finally:
self._mutex.unlock()
def set_key(self, new_key):
try:
self._mutex.lock()
print "NOT IMPLEMENTED"
# TODO: change key
finally:
self._mutex.unlock()
@property
def has_ccid(self):
try:
self._mutex.lock()
return self._dev and self._dev.has_ccid
finally:
self._mutex.unlock()
@property
def mode(self):
return self._mode
@property
def serial(self):
return self._serial
@property
def version(self):
return self._version
def __str__(self):
return self.name
def list_apps(self):
try:
self._mutex.lock()
if self.device_type != 'CCID':
return []
if self._apps is None:
apps = []
appletmanager = QtCore.QCoreApplication.instance() \
.appletmanager
for applet in appletmanager.get_applets():
installed, version = applet.get_status(self)
if installed:
apps.append(applet.aid)
self._apps = apps
return self._apps
finally:
self._mutex.unlock()
class AvailableNeos(QtCore.QThread):
changed = QtCore.Signal(list)
def __init__(self):
super(AvailableNeos, self).__init__()
self._mutex = QtCore.QMutex()
self._neos = []
self._running = True
self._sleep = 1000
def stop(self):
self._running = False
self.wait()
def get(self):
try:
self._mutex.lock()
return self._neos[:]
finally:
self._mutex.unlock()
def run(self):
self.discover_devices() # Discover initial devices.
while self._running:
if QtGui.QApplication.activeWindow(): # Only if we have focus
self.discover_devices()
self.msleep(self._sleep)
def discover_devices(self):
neos = self.get()
existing_devs = []
for neo in neos:
if neo._dev:
neo._mutex.lock()
existing_devs.append(neo._dev)
neo._dev = None
new_neos = []
dead_neos = neos[:]
state_reset = False # Set True after state reset
try:
discovered = open_all_devices(existing_devs)
if self._sleep > 1000: # State reset!
self._sleep = 1000 # Reset sleep time
state_reset = True
except ResetStateException as e:
discovered = e.devices
self._sleep = 3500 # Increase sleep time
for dev in discovered:
for neo in dead_neos[:]:
if dev.serial == neo.serial and dev.version == neo.version \
and dev.device_type == dev.device_type:
neo._set_device(dev)
neo._mutex.unlock()
dead_neos.remove(neo)
break
else:
new_neos.append(YubiKeyNeo(dev))
for neo in dead_neos:
neos.remove(neo)
neo.removed.emit()
neo._mutex.unlock()
if new_neos or dead_neos or state_reset:
self._mutex.lock()
self._neos = neos + new_neos
neos_copy = self._neos[:]
self._mutex.unlock()
self.changed.emit(neos_copy) | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/model/neo.py | neo.py |
from PySide import QtCore, QtNetwork
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from neoman.model.jsapi import JS_API, AppletNotInstalledException
from neoman.networker import NetWorker
from neoman.storage import CONFIG_HOME, capstore
from neoman import messages as m
import os
import json
__all__ = ['Applet', 'AppletManager']
DB_FILE = os.path.join(CONFIG_HOME, "appletdb.json")
class Applet(object):
def __init__(self, aid, name, description, **kwargs):
self.aid = aid
self.name = name
self.description = description
self.latest_version = kwargs.get('version', 'unknown')
self.cap_url = kwargs.get('cap_url', None)
self.cap_sha1 = kwargs.get('cap_sha1', None)
self.allow_uninstall = kwargs.get('allow_uninstall', True)
self._js_version = kwargs.get('js_version', None)
self.tabs = kwargs.get('tabs', {})
def __str__(self):
return self.name
@property
def is_downloaded(self):
return capstore.has_file(self.aid, self.latest_version)
@property
def cap_file(self):
return capstore.get_filename(self.aid, self.latest_version,
self.cap_sha1)
def get_status(self, neo):
installed = False
version = None
try:
with JS_API(neo, self) as api:
installed = True
if self._js_version:
version = api.run(self._js_version)
except AppletNotInstalledException:
pass
return (installed, version)
class AppletManager(object):
def __init__(self):
self._hidden = []
self._applets = []
self._read_db()
self.networker = NetWorker(QtCore.QCoreApplication.instance().worker)
def update(self):
self.networker.download_bg(self._db_url, self._updated)
def _updated(self, data):
if not isinstance(data, QtNetwork.QNetworkReply.NetworkError):
try:
data = json.loads(data.data())
data = self._verify(**data)
with open(DB_FILE, 'w') as db:
json.dump(data, db)
if data['location'] != self._db_url:
self._db_url = data['location']
self.update()
else:
self._read_db()
except:
pass # Ignore
def _verify(self, message, signature):
key = RSA.importKey(self._pub_key)
h = SHA256.new()
h.update(message)
verifier = PKCS1_PSS.new(key)
if verifier.verify(h, signature.decode('base64')):
return json.loads(message.decode('base64'))
raise ValueError("Invalid file signature!")
def _read_db(self):
try:
with open(DB_FILE, 'r') as db:
data = json.load(db)
except:
basedir = QtCore.QCoreApplication.instance().basedir
path = os.path.join(basedir, 'appletdb.json')
with open(path, 'r') as db:
data = json.load(db)
self._applets = []
for applet in data['applets']:
self._applets.append(Applet(**applet))
self._hidden = data['hidden']
self._db_url = data['location']
self._pub_key = data['pubkey']
def get_applets(self):
return self._applets
def get_applet(self, aid):
if aid in self._hidden:
return None
for applet in self._applets:
if aid.startswith(applet.aid):
return applet
return Applet(aid, m.unknown, m.unknown_applet) | yubikey-neo-manager | /yubikey-neo-manager-1.4.0.tar.gz/yubikey-neo-manager-1.4.0/neoman/model/applet.py | applet.py |
from __future__ import print_function
import sys
import argparse
import signal
import pivman.qt_resources # noqa: F401
from PySide import QtGui, QtCore
from pivman.view.main import MainWidget
from pivman import __version__ as version, messages as m
from pivman.piv import YkPiv, libversion as ykpiv_version
from pivman.controller import Controller
from pivman.view.set_pin_dialog import SetPinDialog
from pivman.view.settings_dialog import SettingsDialog
from pivman.yubicommon import qt
ABOUT_TEXT = """
<h2>%s</h2>
%s<br>
%s
<h4>%s</h4>
%%s
<br><br>
""" % (m.app_name, m.copyright, m.version_1, m.libraries)
class PivtoolApplication(qt.Application):
def __init__(self, argv):
super(PivtoolApplication, self).__init__(m, version)
QtCore.QCoreApplication.setOrganizationName(m.organization)
QtCore.QCoreApplication.setOrganizationDomain(m.domain)
QtCore.QCoreApplication.setApplicationName(m.app_name)
args = self._parse_args()
if args.check_only:
self.check_pin()
self.quit()
return
self.ensure_singleton()
self._build_menu_bar()
self._init_window()
def check_pin(self):
try:
controller = Controller(YkPiv())
if controller.is_uninitialized():
print('Device not initialized')
elif controller.is_pin_expired():
dialog = SetPinDialog(controller, None, True)
if dialog.exec_():
QtGui.QMessageBox.information(None, m.pin_changed,
m.pin_changed_desc)
except:
print('No YubiKey PIV applet detected')
def _parse_args(self):
parser = argparse.ArgumentParser(description='YubiKey PIV Manager',
add_help=True)
parser.add_argument('-c', '--check-only', action='store_true')
return parser.parse_args()
def _init_window(self):
self.window.setWindowTitle(m.win_title_1 % self.version)
self.window.setWindowIcon(QtGui.QIcon(':/pivman.png'))
self.window.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.window.setCentralWidget(MainWidget())
self.window.show()
self.window.raise_()
def _build_menu_bar(self):
file_menu = self.window.menuBar().addMenu(m.menu_file)
settings_action = QtGui.QAction(m.action_settings, file_menu)
settings_action.triggered.connect(self._show_settings)
file_menu.addAction(settings_action)
help_menu = self.window.menuBar().addMenu(m.menu_help)
about_action = QtGui.QAction(m.action_about, help_menu)
about_action.triggered.connect(self._about)
help_menu.addAction(about_action)
def _libversions(self):
return 'ykpiv: %s' % ykpiv_version.decode('ascii')
def _about(self):
QtGui.QMessageBox.about(
self.window,
m.about_1 % m.app_name,
ABOUT_TEXT % (self.version, self._libversions())
)
def _show_settings(self):
dialog = SettingsDialog(self.window)
if dialog.exec_():
self.window.centralWidget().refresh()
def main():
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = PivtoolApplication(sys.argv)
sys.exit(app.exec_())
if __name__ == '__main__':
main() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/__main__.py | __main__.py |
from __future__ import print_function
from PySide import QtGui, QtCore
from pivman.controller import Controller
from pivman.piv import YkPiv, PivError, DeviceGoneError
from pivman.storage import settings, SETTINGS
from functools import partial
try:
from Queue import Queue
except ImportError:
from queue import Queue
class Release(object):
def __init__(self, fn):
self._fn = fn
def __del__(self):
self._fn()
def __call__(self):
self._fn()
self._fn = lambda: None
class ControllerWatcher(QtCore.QObject):
_device_found = QtCore.Signal()
_device_lost = QtCore.Signal()
def __init__(self):
super(ControllerWatcher, self).__init__()
self._waiters = Queue()
self._controller = None
self._lock = QtCore.QMutex()
self._lock.lock()
self._worker = QtCore.QCoreApplication.instance().worker
self._worker.post_bg(self._poll, self._release, True)
self.startTimer(2000)
def timerEvent(self, event):
if QtGui.QApplication.activeWindow() and self._lock.tryLock():
self._worker.post_bg(self._poll, self._release, True)
event.accept()
def _release(self, result=None):
if self._controller and not self._waiters.empty():
waiter = self._waiters.get_nowait()
waiter(self._controller, Release(self._release))
else:
self._lock.unlock()
def _poll(self):
reader = settings[SETTINGS.CARD_READER]
if self._controller:
if self._controller.poll():
return
self._controller = None
self._device_lost.emit()
try:
self._controller = Controller(YkPiv(reader=reader))
self._device_found.emit()
except (PivError, DeviceGoneError) as e:
print(e)
def on_found(self, fn, hold_lock=False):
self._device_found.connect(self.wrap(fn, hold_lock))
def on_lost(self, fn):
self._device_lost.connect(fn)
def use(self, fn, hold_lock=False):
if not hold_lock:
def waiter(controller, release):
fn(controller)
else:
waiter = fn
if self._controller and self._lock.tryLock():
waiter(self._controller, Release(self._release))
else:
self._waiters.put(waiter)
def wrap(self, fn, hold_lock=False):
return partial(self.use, fn, hold_lock) | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/watcher.py | watcher.py |
from ctypes import (Structure, POINTER, c_int, c_ubyte, c_char_p, c_long,
c_ulong, c_size_t)
from pivman.yubicommon.ctypes import CLibrary
ykpiv_state = type('ykpiv_state', (Structure,), {})
ykpiv_rc = c_int
class YKPIV(object):
OK = 0
MEMORY_ERROR = -1
PCSC_ERROR = -2
SIZE_ERROR = -3
APPLET_ERROR = -4
AUTHENTICATION_ERROR = -5
RANDOMNESS_ERROR = -6
GENERIC_ERROR = -7
KEY_ERROR = -8
PARSE_ERROR = -9
WRONG_PIN = -10
INVALID_OBJECT = -11
ALGORITHM_ERROR = -12
class OBJ(object):
CAPABILITY = 0x5fc107
CHUID = 0x5fc102
AUTHENTICATION = 0x5fc105 # cert for 9a key
FINGERPRINTS = 0x5fc103
SECURITY = 0x5fc106
FACIAL = 0x5fc108
PRINTED = 0x5fc109
SIGNATURE = 0x5fc10a # cert for 9c key
KEY_MANAGEMENT = 0x5fc10b # cert for 9d key
CARD_AUTH = 0x5fc101 # cert for 9e key
DISCOVERY = 0x7e
KEY_HISTORY = 0x5fc10c
IRIS = 0x5fc121
class ALGO(object):
TDEA = 0x03
RSA1024 = 0x06
RSA2048 = 0x07
ECCP256 = 0x11
ECCP384 = 0x14
class LibYkPiv(CLibrary):
ykpiv_strerror = [ykpiv_rc], c_char_p
ykpiv_strerror_name = [ykpiv_rc], c_char_p
ykpiv_init = [POINTER(POINTER(ykpiv_state)), c_int], ykpiv_rc
ykpiv_done = [POINTER(ykpiv_state)], ykpiv_rc
ykpiv_connect = [POINTER(ykpiv_state), c_char_p], ykpiv_rc
ykpiv_disconnect = [POINTER(ykpiv_state)], ykpiv_rc
ykpiv_transfer_data = [POINTER(ykpiv_state), POINTER(c_ubyte),
POINTER(c_ubyte), c_long, POINTER(c_ubyte),
POINTER(c_ulong), POINTER(c_int)], ykpiv_rc
ykpiv_authenticate = [POINTER(ykpiv_state), POINTER(c_ubyte)], ykpiv_rc
ykpiv_set_mgmkey = [POINTER(ykpiv_state), POINTER(c_ubyte)], ykpiv_rc
ykpiv_hex_decode = [c_char_p, c_size_t, POINTER(c_ubyte), POINTER(c_size_t)
], ykpiv_rc
ykpiv_sign_data = [POINTER(ykpiv_state), POINTER(c_ubyte), c_size_t,
POINTER(c_ubyte), POINTER(c_size_t), c_ubyte, c_ubyte
], ykpiv_rc
ykpiv_get_version = [POINTER(ykpiv_state), c_char_p, c_size_t], ykpiv_rc
ykpiv_verify = [POINTER(ykpiv_state), c_char_p, POINTER(c_int)], ykpiv_rc
ykpiv_fetch_object = [POINTER(ykpiv_state), c_int, POINTER(c_ubyte),
POINTER(c_ulong)], ykpiv_rc
ykpiv_save_object = [POINTER(ykpiv_state), c_int, POINTER(c_ubyte),
c_size_t], ykpiv_rc
ykpiv_check_version = [c_char_p], c_char_p
ykpiv = LibYkPiv('ykpiv', '1') | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/libykpiv.py | libykpiv.py |
from pivman.utils import test, der_read, is_macos_sierra_or_later
from pivman.piv import PivError, WrongPinError
from pivman.storage import settings, SETTINGS
from pivman.view.utils import get_active_window, get_text
from pivman import messages as m
from pivman.yubicommon.compat import text_type, byte2int, int2byte
from PySide import QtGui, QtNetwork
from datetime import timedelta
from hashlib import pbkdf2_hmac
from binascii import a2b_hex
import os
import re
import time
import struct
YKPIV_OBJ_PIVMAN_DATA = 0x5fff00
TAG_PIVMAN_DATA = 0x80 # Wrapper for pivman data
TAG_FLAGS_1 = 0x81 # Flags 1
TAG_SALT = 0x82 # Salt used for management key derivation
TAG_PIN_TIMESTAMP = 0x83 # When the PIN was last changed
FLAG1_PUK_BLOCKED = 0x01 # PUK is blocked
AUTH_SLOT = '9a'
ENCRYPTION_SLOT = '9d'
DEFAULT_AUTH_SUBJECT = "/CN=Yubico PIV Authentication"
DEFAULT_ENCRYPTION_SUBJECT = "/CN=Yubico PIV Encryption"
DEFAULT_VALID_DAYS = 10950 # 30 years
NEO_MAX_CERT_LEN = 1024 * 2 - 23
YK4_MAX_CERT_LEN = 1024 * 3 - 23
def parse_pivtool_data(raw_data):
rest, _ = der_read(raw_data, TAG_PIVMAN_DATA)
data = {}
while rest:
t, v, rest = der_read(rest)
data[t] = v
return data
def serialize_pivtool_data(data): # NOTE: Doesn't support values > 0x80 bytes.
buf = b''
for k, v in sorted(data.items()):
buf += int2byte(k) + int2byte(len(v)) + v
return int2byte(TAG_PIVMAN_DATA) + int2byte(len(buf)) + buf
def has_flag(data, flagkey, flagmask):
flags = byte2int(data.get(flagkey, b'\0')[0])
return bool(flags & flagmask)
def set_flag(data, flagkey, flagmask, value=True):
flags = byte2int(data.get(flagkey, b'\0')[0])
if value:
flags |= flagmask
else:
flags &= ~flagmask
data[flagkey] = int2byte(flags)
def derive_key(pin, salt):
if pin is None:
raise ValueError('PIN must not be None!')
if isinstance(pin, text_type):
pin = pin.encode('utf8')
return pbkdf2_hmac('sha1', pin, salt, 10000, dklen=24)
def is_hex_key(string):
try:
return bool(re.compile(r'^[a-fA-F0-9]{48}$').match(string))
except:
return False
class Controller(object):
def __init__(self, key):
self._key = key
self._authenticated = False
try:
self._raw_data = self._key.fetch_object(YKPIV_OBJ_PIVMAN_DATA)
# TODO: Remove in a few versions...
if byte2int(self._raw_data[0]) != TAG_PIVMAN_DATA:
self._data = {}
self._data[TAG_PIN_TIMESTAMP] = self._raw_data
self._data[TAG_SALT] = self._key.fetch_object(
YKPIV_OBJ_PIVMAN_DATA + 1)
else:
# END legacy stuff
self._data = parse_pivtool_data(self._raw_data)
except PivError:
self._raw_data = serialize_pivtool_data({})
self._data = {}
def poll(self):
return test(self._key._read_version)
def reconnect(self):
self._key.reconnect()
def _save_data(self):
raw_data = serialize_pivtool_data(self._data)
if raw_data != self._raw_data:
self.ensure_authenticated()
self._key.save_object(YKPIV_OBJ_PIVMAN_DATA, raw_data)
self._raw_data = raw_data
@property
def version(self):
return self._key.version
@property
def version_tuple(self):
return tuple(map(int, self.version.split(b'.')))
@property
def authenticated(self):
return self._authenticated
@property
def pin_is_key(self):
return TAG_SALT in self._data
@property
def pin_blocked(self):
return self._key.pin_blocked
@property
def puk_blocked(self):
return has_flag(self._data, TAG_FLAGS_1, FLAG1_PUK_BLOCKED)
def verify_pin(self, pin):
if len(pin) > 8:
raise ValueError('PIN must be no longer than 8 bytes!')
self._key.verify_pin(pin)
def ensure_pin(self, pin=None, window=None):
if window is None:
window = get_active_window()
if pin is not None:
try:
self.verify_pin(pin)
return pin
except WrongPinError as e:
if e.blocked:
raise
QtGui.QMessageBox.warning(window, m.error, str(e))
except ValueError as e:
QtGui.QMessageBox.warning(window, m.error, str(e))
pin, status = get_text(
window, m.enter_pin, m.pin_label, QtGui.QLineEdit.Password)
if not status:
raise ValueError('PIN entry aborted!')
return self.ensure_pin(pin, window)
def ensure_authenticated(self, key=None, window=None):
if self.authenticated or test(self.authenticate, catches=ValueError):
return
if window is None:
window = get_active_window()
if self.pin_is_key:
key = self.ensure_pin(key, window)
self.authenticate(key)
return
elif key is not None:
try:
self.authenticate(key)
return
except ValueError:
pass
self._do_ensure_auth(None, window)
def _do_ensure_auth(self, key, window):
if key is not None:
try:
self.authenticate(key)
return
except ValueError as e:
QtGui.QMessageBox.warning(window, m.error, str(e))
key, status = get_text(window, m.enter_key, m.key_label)
if not status:
raise ValueError('Key entry aborted!')
self._do_ensure_auth(key, window)
def reset_device(self):
self._key.reset_device()
def authenticate(self, key=None):
salt = self._data.get(TAG_SALT)
if key is not None and salt is not None:
key = derive_key(key, salt)
elif is_hex_key(key):
key = a2b_hex(key)
self._authenticated = False
if test(self._key.authenticate, key, catches=PivError):
self._authenticated = True
else:
raise ValueError(m.wrong_key)
def is_uninitialized(self):
return not self._data and test(self._key.authenticate)
def _invalidate_puk(self):
set_flag(self._data, TAG_FLAGS_1, FLAG1_PUK_BLOCKED)
for i in range(8): # Invalidate the PUK
test(self._key.set_puk, '', '000000', catches=ValueError)
def initialize(self, pin, puk=None, key=None, old_pin='123456',
old_puk='12345678'):
if not self.authenticated:
self.authenticate()
if key is None: # Derive key from PIN
self._data[TAG_SALT] = b'' # Used as a marker for change_pin
else:
self.set_authentication(key)
if puk is None:
self._invalidate_puk()
else:
self._key.set_puk(old_puk, puk)
self.change_pin(old_pin, pin)
def setup_for_macos(self, pin):
"""Generate self-signed certificates in slot 9a and 9d
to allow pairing a YubiKey with a user account on macOS"""
auth_key = self.generate_key(AUTH_SLOT, 'ECCP256')
auth_cert = self.selfsign_certificate(
AUTH_SLOT, pin, auth_key,
DEFAULT_AUTH_SUBJECT, DEFAULT_VALID_DAYS)
self.import_certificate(auth_cert, AUTH_SLOT)
encryption_key = self.generate_key(ENCRYPTION_SLOT, 'ECCP256')
encryption_cert = self.selfsign_certificate(
ENCRYPTION_SLOT, pin, encryption_key,
DEFAULT_ENCRYPTION_SUBJECT, DEFAULT_VALID_DAYS)
self.import_certificate(encryption_cert, ENCRYPTION_SLOT)
def set_authentication(self, new_key, is_pin=False):
if not self.authenticated:
raise ValueError('Not authenticated')
if is_pin:
self.verify_pin(new_key)
salt = os.urandom(16)
key = derive_key(new_key, salt)
self._data[TAG_SALT] = salt
self._key.set_authentication(key)
# Make sure PUK is invalidated:
if not has_flag(self._data, TAG_FLAGS_1, FLAG1_PUK_BLOCKED):
self._invalidate_puk()
else:
if is_hex_key(new_key):
new_key = a2b_hex(new_key)
self._key.set_authentication(new_key)
if self.pin_is_key:
del self._data[TAG_SALT]
self._save_data()
def change_pin(self, old_pin, new_pin):
if len(new_pin) < 6:
raise ValueError('PIN must be at least 6 characters')
self.verify_pin(old_pin)
if self.pin_is_key or self.does_pin_expire():
self.ensure_authenticated(old_pin)
self._key.set_pin(new_pin)
# Update management key if needed:
if self.pin_is_key:
self.set_authentication(new_pin, True)
if self.does_pin_expire():
self._data[TAG_PIN_TIMESTAMP] = struct.pack('i', int(time.time()))
self._save_data()
def reset_pin(self, puk, new_pin):
if len(new_pin) < 6:
raise ValueError('PIN must be at least 6 characters')
try:
self._key.reset_pin(puk, new_pin)
except WrongPinError as e:
if e.blocked:
set_flag(self._data, TAG_FLAGS_1, FLAG1_PUK_BLOCKED)
raise
def change_puk(self, old_puk, new_puk):
if self.puk_blocked:
raise ValueError('PUK is disabled and cannot be changed')
if len(new_puk) < 6:
raise ValueError('PUK must be at least 6 characters')
try:
self._key.set_puk(old_puk, new_puk)
except WrongPinError as e:
if e.blocked:
set_flag(self._data, TAG_FLAGS_1, FLAG1_PUK_BLOCKED)
raise
def update_chuid(self):
if not self.authenticated:
raise ValueError('Not authenticated')
self._key.set_chuid()
def generate_key(self, slot, algorithm='RSA2048', pin_policy=None,
touch_policy=False):
if not self.authenticated:
raise ValueError('Not authenticated')
if pin_policy == 'default':
pin_policy = None
if slot in self.certs:
self.delete_certificate(slot)
return self._key.generate(slot, algorithm, pin_policy, touch_policy)
def create_csr(self, slot, pin, pubkey, subject):
self.verify_pin(pin)
if not self.authenticated:
raise ValueError('Not authenticated')
return self._key.create_csr(subject, pubkey, slot)
def selfsign_certificate(self, slot, pin, pubkey, subject, valid_days=365):
self.verify_pin(pin)
if not self.authenticated:
raise ValueError('Not authenticated')
return self._key.create_selfsigned_cert(
subject, pubkey, slot, valid_days)
def does_pin_expire(self):
return bool(settings[SETTINGS.PIN_EXPIRATION])
def get_pin_last_changed(self):
data = self._data.get(TAG_PIN_TIMESTAMP)
if data is not None:
data = struct.unpack('i', data)[0]
return data
def get_pin_days_left(self):
validity = settings[SETTINGS.PIN_EXPIRATION]
if not validity:
return -1
last_changed = self.get_pin_last_changed()
if last_changed is None:
return 0
time_passed = timedelta(seconds=time.time() - last_changed)
time_left = timedelta(days=validity) - time_passed
return max(time_left.days, 0)
def is_pin_expired(self):
if not self.does_pin_expire():
return False
last_changed = self.get_pin_last_changed()
if last_changed is None:
return True
delta = timedelta(seconds=time.time() - last_changed)
return delta.days > 30
@property
def certs(self):
return self._key.certs
def get_certificate(self, slot):
data = self._key.read_cert(slot)
if data is None:
return None
return QtNetwork.QSslCertificate.fromData(data, QtNetwork.QSsl.Der)[0]
def import_key(self, data, slot, frmt='PEM', password=None, pin_policy=None,
touch_policy=False):
if not self.authenticated:
raise ValueError('Not authenticated')
if pin_policy == 'default':
pin_policy = None
self._key.import_key(data, slot, frmt, password, pin_policy,
touch_policy)
def import_certificate(self, cert, slot, frmt='PEM', password=None):
if not self.authenticated:
raise ValueError('Not authenticated')
try:
self._key.import_cert(cert, slot, frmt, password)
except ValueError:
cert_len = len(cert)
if cert_len > NEO_MAX_CERT_LEN and self.version_tuple < (4, 2, 7):
raise ValueError(
'Certificate too large, maximum is '
+ str(NEO_MAX_CERT_LEN)
+ ' bytes (was '
+ str(cert_len) + ' bytes).')
elif cert_len > YK4_MAX_CERT_LEN:
raise ValueError(
'Certificate too large, maximum is '
+ str(YK4_MAX_CERT_LEN)
+ ' bytes (was '
+ str(cert_len) + ' bytes).')
else:
raise
self.update_chuid()
def delete_certificate(self, slot):
if not self.authenticated:
raise ValueError('Not authenticated')
self._key.delete_cert(slot)
def should_show_macos_dialog(self):
return is_macos_sierra_or_later() \
and AUTH_SLOT not in self.certs \
and ENCRYPTION_SLOT not in self.certs | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/controller.py | controller.py |
from getpass import getuser
from pivman import messages as m
from pivman.yubicommon.compat import byte2int
import re
import subprocess
import os
import tempfile
import sys
def has_ca():
try:
if sys.platform == 'win32':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(
['certutil', '-dump'], stdout=subprocess.PIPE,
startupinfo=startupinfo)
output, _ = p.communicate()
# 'certutil -dump' returns one line when no CA is available.
return len(str.splitlines(output)) > 1
except OSError:
pass
return False
def request_cert_from_ca(csr, cert_tmpl):
try:
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(csr)
csr_fn = f.name
with tempfile.NamedTemporaryFile() as f:
cert_fn = f.name
p = subprocess.Popen(['certreq', '-submit', '-attrib',
'CertificateTemplate:%s' % cert_tmpl, csr_fn,
cert_fn], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode != 0:
raise ValueError(m.certreq_error_1 % out)
with open(cert_fn, 'r') as cert:
return cert.read()
except OSError as e:
raise ValueError(m.certreq_error_1 % e)
finally:
os.remove(csr_fn)
if os.path.isfile(cert_fn):
os.remove(cert_fn)
def test(fn, *args, **kwargs):
e_type = kwargs.pop('catches', Exception)
try:
fn(*args, **kwargs)
return True
except e_type:
return False
# https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/504.mspx?mfr=true
# Password must contain characters from three of the following four categories:
CATEGORIES = [
lambda c: c.isupper(), # English uppercase characters (A through Z)
lambda c: c.islower(), # English lowercase characters (a through z)
re.compile(r'[0-9]').match, # Base 10 digits (0 through 9)
re.compile(r'\W', re.UNICODE).match
# Nonalphanumeric characters (e.g., !, $, #, %)
]
def contains_category(password, category):
return any(category(p) for p in password)
def complexity_check(password):
# Be at least six characters in length
if len(password) < 6:
return False
# Contain characters from at least 3 groups:
if sum(contains_category(password, c) for c in CATEGORIES) < 3:
return False
# Not contain all or part of the user's account name
parts = [p for p in re.split(r'\W', getuser().lower()) if len(p) >= 3]
if any(part in password.lower() for part in parts):
return False
return True
def der_read(der_data, expected_t=None):
t = byte2int(der_data[0])
if expected_t is not None and expected_t != t:
raise ValueError('Wrong tag. Expected: %x, got: %x' % (expected_t, t))
l = byte2int(der_data[1])
offs = 2
if l > 0x80:
n_bytes = l - 0x80
l = b2len(der_data[offs:offs + n_bytes])
offs = offs + n_bytes
v = der_data[offs:offs + l]
rest = der_data[offs + l:]
if expected_t is None:
return t, v, rest
return v, rest
def b2len(bs):
l = 0
for b in bs:
l *= 256
l += byte2int(b)
return l
def is_macos_sierra_or_later():
if sys.platform == 'darwin':
from platform import mac_ver
mac_version = tuple(int(x) for x in mac_ver()[0].split('.'))
return mac_version >= (10, 12)
return False | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/utils.py | utils.py |
import subprocess
import sys
import os
CMD = 'yubico-piv-tool'
if getattr(sys, 'frozen', False):
# we are running in a PyInstaller bundle
basedir = sys._MEIPASS
else:
# we are running in a normal Python environment
basedir = os.path.dirname(__file__)
def find_cmd():
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
cmd = CMD + '.exe' if sys.platform == 'win32' else CMD
paths = [basedir] + os.environ.get('PATH', '').split(os.pathsep)
for path in paths:
path = path.strip('"')
fpath = os.path.join(path, cmd)
if is_exe(fpath):
return fpath
return None
def check(status, err):
if status != 0:
raise ValueError('Error: %s' % err)
def set_arg(args, opt, value):
args = list(args)
if opt != '-a' and opt in args:
index = args.index(opt)
if value is None:
del args[index]
del args[index]
else:
args[index + 1] = value
elif value is not None:
args.extend([opt, value])
return args
class YkPivCmd(object):
_pin = None
_key = None
def __init__(self, cmd=find_cmd(), verbosity=0, reader=None, key=None):
self._base_args = [cmd]
if verbosity > 0:
self._base_args.extend(['-v', str(verbosity)])
if reader:
self._base_args.extend(['-r', reader])
if key:
self._key = key
def set_arg(self, opt, value):
if isinstance(value, bytes):
value = value.decode('utf8')
self._base_args = set_arg(self._base_args, opt, value)
def run(self, *args, **kwargs):
full_args = list(self._base_args)
new_args = list(args)
while new_args:
full_args = set_arg(full_args, new_args.pop(0), new_args.pop(0))
if '-k' in full_args: # Workaround for passing key in 1.1.0
i = full_args.index('-k')
full_args = full_args[:i] + ['-k' + full_args[i+1]] \
+ full_args[i+2:]
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
out, err = p.communicate(**kwargs)
check(p.returncode, err)
return out
def get_startup_info(self):
if sys.platform == 'win32': # Avoid showing console window on Windows
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
else:
startupinfo = None
return startupinfo
def status(self):
return self.run('-a', 'status')
def change_pin(self, new_pin):
if self._pin is None:
raise ValueError('PIN has not been verified')
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'change-pin')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(self._pin + '\n')
p.stdin.write(new_pin + '\n')
p.stdin.flush()
out, err = p.communicate()
check(p.returncode, err)
self._pin = new_pin
def change_puk(self, old_puk, new_puk):
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'change-puk')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(old_puk + '\n')
p.stdin.write(new_puk + '\n')
p.stdin.flush()
out, err = p.communicate()
check(p.returncode, err)
def reset_pin(self, puk, new_pin):
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'unblock-pin')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(puk + '\n')
p.stdin.write(new_pin + '\n')
p.stdin.flush()
out, err = p.communicate()
check(p.returncode, err)
def set_chuid(self):
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'set-chuid')
if self._key is not None:
full_args.append('-k')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
if self._key is not None:
p.stdin.write(self._key + '\n')
p.stdin.flush()
out, err = p.communicate()
check(p.returncode, err)
def generate(self, slot, algorithm, pin_policy, touch_policy):
full_args = list(self._base_args)
full_args = set_arg(full_args, '-s', slot)
full_args = set_arg(full_args, '-a', 'generate')
full_args = set_arg(full_args, '-A', algorithm)
full_args = set_arg(full_args, '--pin-policy', pin_policy)
full_args = set_arg(
full_args, '--touch-policy', 'always' if touch_policy else 'never')
full_args.append('-k')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(self._key + '\n')
p.stdin.flush()
out, err = p.communicate()
check(p.returncode, err)
return out
def create_csr(self, subject, pem, slot):
if self._pin is None:
raise ValueError('PIN has not been verified')
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'verify-pin')
full_args = set_arg(full_args, '-s', slot)
full_args = set_arg(full_args, '-a', 'request-certificate')
full_args = set_arg(full_args, '-S', subject)
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(self._pin + '\n')
p.stdin.flush()
out, err = p.communicate(input=pem)
check(p.returncode, err)
return out
def create_ssc(self, subject, pem, slot, valid_days=365):
if self._pin is None:
raise ValueError('PIN has not been verified')
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'verify-pin')
full_args = set_arg(full_args, '-s', slot)
full_args = set_arg(full_args, '-a', 'selfsign-certificate')
full_args = set_arg(full_args, '-S', subject)
full_args = set_arg(full_args, '--valid-days', str(valid_days))
full_args.append('-k')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(self._pin + '\n')
p.stdin.write(self._key + '\n')
p.stdin.flush()
out, err = p.communicate(input=pem)
check(p.returncode, err)
return out
def import_cert(self, data, slot, frmt='PEM', password=None):
return self._do_import('import-cert', data, slot, frmt, password)
def import_key(self, data, slot, frmt, password, pin_policy, touch_policy):
return self._do_import('import-key', data, slot, frmt, password,
'--pin-policy', pin_policy, '--touch-policy',
'always' if touch_policy else 'never')
def _do_import(self, action, data, slot, frmt, password, *args):
if self._key is None:
raise ValueError('Management key has not been provided')
full_args = list(self._base_args)
full_args = set_arg(full_args, '-s', slot)
full_args = set_arg(full_args, '-K', frmt)
full_args = set_arg(full_args, '-a', action)
new_args = list(args)
while new_args:
full_args = set_arg(full_args, new_args.pop(0), new_args.pop(0))
full_args.append('-k')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
if password is not None:
p.stdin.write(password + '\n')
p.stdin.write(self._key + '\n')
p.stdin.flush()
# A small sleep is needed to get yubico-piv-tool
# to read properly in all cases.
import time
time.sleep(0.1)
out, err = p.communicate(input=data)
check(p.returncode, err)
return out
def delete_cert(self, slot):
if self._key is None:
raise ValueError('Management key has not been provided')
full_args = list(self._base_args)
full_args = set_arg(full_args, '-a', 'delete-certificate')
full_args = set_arg(full_args, '-s', slot)
full_args.append('-k')
full_args.append('--stdin-input')
p = subprocess.Popen(full_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
startupinfo=self.get_startup_info())
p.stdin.write(self._key + '\n')
p.stdin.flush()
out, err = p.communicate()
check(p.returncode, err)
return out | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/piv_cmd.py | piv_cmd.py |
import os
from pivman import messages as m
from pivman.piv import CERT_SLOTS
from pivman.yubicommon import qt
from PySide import QtCore
from collections import namedtuple
from getpass import getuser
from sys import platform
__all__ = [
'CONFIG_HOME',
'SETTINGS',
'settings'
]
CONFIG_HOME = os.path.join(os.path.expanduser('~'), '.pivman')
Setting = namedtuple('Setting', 'key default type')
win = platform == 'win32'
def default_outs():
if win:
return ['ssc', 'csr', 'ca']
else:
return ['ssc', 'csr']
class SETTINGS:
ALGORITHM = Setting('algorithm', 'RSA2048', str)
CARD_READER = Setting('card_reader', None, str)
CERTREQ_TEMPLATE = Setting('certreq_template', None, str)
COMPLEX_PINS = Setting('complex_pins', False, bool)
ENABLE_IMPORT = Setting('enable_import', True, bool)
OUT_TYPE = Setting('out_type', 'ca' if win else 'ssc', str)
PIN_AS_KEY = Setting('pin_as_key', True, bool)
PIN_EXPIRATION = Setting('pin_expiration', 0, int)
PIN_POLICY = Setting('pin_policy', None, str)
PIN_POLICY_SLOTS = Setting('pin_policy_slots', [], list)
SHOWN_OUT_FORMS = Setting('shown_outs', default_outs(), list)
SHOWN_SLOTS = Setting('shown_slots', sorted(CERT_SLOTS.keys()), list)
SUBJECT = Setting('subject', '/CN=%s' % getuser(), str)
TOUCH_POLICY = Setting('touch_policy', False, bool)
TOUCH_POLICY_SLOTS = Setting('touch_policy_slots', [], list)
class SettingsOverlay(object):
def __init__(self, master, overlay):
self._master = master
self._overlay = overlay
def __getattr__(self, method_name):
return getattr(self._overlay, method_name)
def rename(self, new_name):
raise NotImplementedError()
def value(self, setting, default=None):
"""Give preference to master."""
key, default, d_type = setting
val = self._master.value(key, self._overlay.value(key, default))
if not isinstance(val, d_type):
val = qt.convert_to(val, d_type)
return val
def setValue(self, setting, value):
self._overlay.setValue(setting.key, value)
def remove(self, setting):
self._overlay.remove(setting.key)
def childKeys(self):
"""Combine keys of master and overlay."""
return list(set(self._master.childKeys() + self._overlay.childKeys()))
def is_locked(self, setting):
return self._master.contains(setting.key)
def __repr__(self):
return 'Overlay(%s, %s)' % (self._master, self._overlay)
settings = qt.PySettings(SettingsOverlay(
QtCore.QSettings(m.organization, m.app_name),
qt.Settings.wrap(os.path.join(CONFIG_HOME, 'settings.ini'),
QtCore.QSettings.IniFormat).get_group('settings')
)) | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/storage.py | storage.py |
# Resource object code
#
# Created: ons apr 19 10:49:59 2017
# by: The Resource Compiler for PySide (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = b"\x00\x00\x00\x5c<RCC>\x0a<qresource>\x0a<file>qt_resources.qrc</file>\x0a<file>pivman.png</file>\x0a</qresource>\x0a</RCC>\x0a\x00\x00\x09R\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x000\x00\x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xde\x0a\x0e\x0b9/\xe7\x8f\xe7o\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x08\xb6IDATh\xde\xc5\x9amlS\xe7\x15\xc7\x7f\xf7\xda\xb1\x89\xf3B^L\xb2\x94\x10')I\x03\x1d/\xa5\xa5I \x14\xe7\xcb\x90h\xd9P\xa5\xee\x1d4Qi\xd3\xb4\x0f\xdb:WUU\x98T!\xfa\xa12H\x93\xa6IU\xa5\x22\x15iUWib\xeb\xba\xa9l\xab\x03iF\x15\xc2\xebX\x03\x09\x858$,$!\xc1\x8e\x13'\xf6}\xd9\x87<\x09\xbe\xbe\xd7\x8e\x1d\xdc\xee\xe4S\xec{\xcfs\xces\xces\xce\xff\xfc\x1fK\xe4P\xfc\x1d\xed\x0e`\x05\xe0\x04lI_\xab\xc0\x1c0\xeb\xf3\x06b\xb9ZS\xca\x81\xd1%\xc03\xc0\x16\xa0\x09\xa8\x03V\x03\xc5\x09\xfau \x0c\x0c\x03\xb7\x80k@\x0f\xd0\xe5\xf3\x06&\xff/\x0e\xf8;\xda\xeb\x81\x83\xc0nal~\x96*\xa2\xc0\x14\xf0\x11\xf0\xba\xcf\x1b\x08~%\x0e\xf8;\xda\xd7\x00\xaf\x02?%\xb7\xf2\x16\xf0\x06p\xdb\xe7\x0d\xe89w\xc0\xdf\xd1^\x08\xbc\x04\xfc\x1c(\xe3\xcb\x91\x09\xe07\xc01\x9f7\x10\xc9\x99\x03\xfe\x8e\xf6J\xe0\xaf\x22\xcf\xd3\x8a\xaekhh\xe8\xba&R\x7f~\x19I\x92\x91\x91\x91$9\x93%/\x02\xbb}\xde\xc0\xc8C;\xe0\xefh\xdf\x0c\x9c\x03\xec\x96\x06\xa3#\x01\x0e\x9b\x0b\x87\xdd\x85\xdbUGeQ#e.\x0f\xf9y\xc5\xf3\xc9\x1e\x0f31\x13\xe4n\xa4\x9f\xb1\xe9\x9b\xc4\x95\x19b\xea\x0c\xfa\xbck\xa9\x96\x8e\x01O\xfb\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xe2y`g2\xb5\x98\x8a\xdc\xfd\x1a\x10\x04,OPu\xc9F\xf6>~\x18\xa7\xbd(G\xe4\xee\x14'\xaf\x1eJG\xee\xc6\x80\x9a\x8c\xc8\xdd\x04'6\x09z}\x85\x15\xbd.K6v5\xbeLc\x85\x17\x87-\x7fY\x86\xc7\xd5(\xd7F?\xe1T\xdf\xd1E\x9dV`\x14h\xf5y\x03\x17\xb3\xba\x1f\x10N\xec\x05\xde\xb7\x8e\xc4\xfc\x05GEa\x03\x8f\xad\xda9\x7f\xc1Q\xdcd\xe08Sa\x9b\x91p/\xc1\xc9\x1e\xae\x8f\x9df4\xd2/J\xa5\x94\xca\xf8\xef\xf8\xbc\x81?\xa5\xd2\x97\xe9\x15S7\x90\x97\xaa\xfe?\xb8b*\xc0] \xae\x98\xf2k\xc4$5\x8f\xe7\xefE\x07\x19\x9d\x9a\xbfb\x8a)\xd3\x8b\xf0`\x89+\xa6\x96T;\x9f\xb1\x03\xc2\x89J\xe0/\x0b\x5cL\xda\x86\x96\x9bK\xbe\xf3\xc0\xb3V9\xbf,\x07\x84\x13\x05\x82\x9f\xff\xa5`\xc6\xbe\x0c\x09\x01\xc7\x80\xa3\xc9\xd5\xe6\xa1\x1dHp\xa4F\x90\xab?\xce\xb1\xf1o\x03G\xb2\xbd\xb1\x7f\x98\x9f\x1ax\x84#{DD\x96\xf3S\x830\xf0!p8\x11\x1e|%\x0e$8R,\x88\xd6\xa7\x80\xf5\x821[\xf8\xb1\x87\x9c0\x80\x87\xc5\x18x\x0b\xe8\x15\x85\xa1s\x01U.W\xa4\x5c\xe6\x80\xbf\xa3\xdd)\xfa\x86\xc3\x02\xa6(\xa2\xb2\xcc\xfa\xbc\x81\xb9\x5c\xad\xf9?\xb4\xddFJx\xea]\xf1\x00\x00\x00\x00IEND\xaeB`\x82"
qt_resource_name = b"\x00\x10\x08X\xa8#\x00q\x00t\x00_\x00r\x00e\x00s\x00o\x00u\x00r\x00c\x00e\x00s\x00.\x00q\x00r\x00c\x00\x0a\x03\x8f\xb6\xe7\x00p\x00i\x00v\x00m\x00a\x00n\x00.\x00p\x00n\x00g"
qt_resource_struct = b"\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00&\x00\x00\x00\x00\x00\x01\x00\x00\x00`\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/qt_resources.py | qt_resources.py |
from pivman.libykpiv import YKPIV, ykpiv, ykpiv_state
from pivman.piv_cmd import YkPivCmd
from pivman import messages as m
from pivman.utils import der_read
from pivman.yubicommon.compat import text_type, int2byte
from ctypes import (POINTER, byref, create_string_buffer, sizeof, c_ubyte,
c_size_t, c_int)
from binascii import a2b_hex, b2a_hex
import re
_YKPIV_MIN_VERSION = b'1.2.0'
libversion = ykpiv.ykpiv_check_version(_YKPIV_MIN_VERSION)
if not libversion:
raise Exception('libykpiv >= %s required' % _YKPIV_MIN_VERSION)
class DeviceGoneError(Exception):
def __init__(self):
super(DeviceGoneError, self).__init__(m.communication_error)
class PivError(Exception):
def __init__(self, code):
message = ykpiv.ykpiv_strerror(code)
super(PivError, self).__init__(code, message)
self.code = code
self.message = message
def __str__(self):
return m.ykpiv.ykpiv_error_2 % (self.code, self.message)
class WrongPinError(ValueError):
m_tries_1 = m.wrong_pin_tries_1
m_blocked = m.pin_blocked
def __init__(self, tries):
super(WrongPinError, self).__init__(self.m_tries_1 % tries
if tries > 0 else self.m_blocked)
self.tries = tries
@property
def blocked(self):
return self.tries == 0
class WrongPukError(WrongPinError):
m_tries_1 = m.wrong_puk_tries_1
m_blocked = m.puk_blocked
def check(rc):
if rc == YKPIV.PCSC_ERROR:
raise DeviceGoneError()
elif rc != YKPIV.OK:
raise PivError(rc)
def wrap_puk_error(error):
match = TRIES_PATTERN.search(str(error))
if match:
raise WrongPukError(int(match.group(1)))
raise WrongPukError(0)
KEY_LEN = 24
DEFAULT_KEY = a2b_hex(b'010203040506070801020304050607080102030405060708')
CERT_SLOTS = {
'9a': YKPIV.OBJ.AUTHENTICATION,
'9c': YKPIV.OBJ.SIGNATURE,
'9d': YKPIV.OBJ.KEY_MANAGEMENT,
'9e': YKPIV.OBJ.CARD_AUTH
}
ATTR_NAME = 'name'
TRIES_PATTERN = re.compile(r'now (\d+) tries')
class YkPiv(object):
def __init__(self, verbosity=0, reader=None):
self._cmd = YkPivCmd(verbosity=verbosity, reader=reader)
self._state = POINTER(ykpiv_state)()
if not reader:
reader = 'Yubikey'
self._chuid = None
self._ccc = None
self._pin_blocked = False
self._verbosity = verbosity
self._reader = reader
self._certs = {}
check(ykpiv.ykpiv_init(byref(self._state), self._verbosity))
self._connect()
self._read_status()
if not self.chuid:
try:
self.set_chuid()
except ValueError:
pass # Not autheniticated, perhaps?
if not self.ccc:
try:
self.set_ccc()
except ValueError:
pass # Not autheniticated, perhaps?
def reconnect(self):
check(ykpiv.ykpiv_disconnect(self._state))
self._reset()
def _connect(self):
check(ykpiv.ykpiv_connect(self._state, self._reader.encode('utf8')))
self._read_version()
self._read_chuid()
def _read_status(self):
try:
check(ykpiv.ykpiv_disconnect(self._state))
data = self._cmd.run('-a', 'status')
lines = data.splitlines()
chunk = []
while lines:
line = lines.pop(0)
if chunk and not line.startswith(b'\t'):
self._parse_status(chunk)
chunk = []
chunk.append(line)
if chunk:
self._parse_status(chunk)
self._status = data
finally:
self._reset()
def _parse_status(self, chunk):
parts, rest = chunk[0].split(), chunk[1:]
if parts[0] == b'Slot' and rest:
self._parse_slot(parts[1][:-1], rest)
elif parts[0] == b'PIN':
self._pin_blocked = parts[-1] == '0'
def _parse_slot(self, slot, lines):
slot = slot.decode('ascii')
self._certs[slot] = dict(l.strip().split(b':\t', 1) for l in lines)
def _read_version(self):
v = create_string_buffer(10)
check(ykpiv.ykpiv_get_version(self._state, v, sizeof(v)))
self._version = v.value
def _read_chuid(self):
try:
chuid_data = self.fetch_object(YKPIV.OBJ.CHUID)[29:29 + 16]
self._chuid = b2a_hex(chuid_data)
except PivError: # No chuid set?
self._chuid = None
def _read_ccc(self):
try:
ccc_data = self.fetch_object(YKPIV.OBJ.CAPABILITY)[29:29 + 16]
self._ccc = b2a_hex(ccc_data)
except PivError: # No ccc set?
self._ccc = None
def __del__(self):
check(ykpiv.ykpiv_done(self._state))
def _reset(self):
self._connect()
if self._cmd._pin is not None:
self.verify_pin(self._cmd._pin)
if self._cmd._key is not None:
self.authenticate(a2b_hex(self._cmd._key))
@property
def version(self):
return self._version
@property
def chuid(self):
return self._chuid
@property
def ccc(self):
return self._ccc
@property
def pin_blocked(self):
return self._pin_blocked
@property
def certs(self):
return dict(self._certs)
def set_chuid(self):
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.set_chuid()
finally:
self._reset()
def set_ccc(self):
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.run('-a', 'set-ccc')
finally:
self._reset()
def authenticate(self, key=None):
if key is None:
key = DEFAULT_KEY
elif len(key) != KEY_LEN:
raise ValueError('Key must be %d bytes' % KEY_LEN)
c_key = (c_ubyte * KEY_LEN).from_buffer_copy(key)
check(ykpiv.ykpiv_authenticate(self._state, c_key))
self._cmd._key = b2a_hex(key)
if not self.chuid:
self.set_chuid()
def set_authentication(self, key):
if len(key) != KEY_LEN:
raise ValueError('Key must be %d bytes' % KEY_LEN)
c_key = (c_ubyte * len(key)).from_buffer_copy(key)
check(ykpiv.ykpiv_set_mgmkey(self._state, c_key))
self._cmd._key = b2a_hex(key)
def verify_pin(self, pin):
if isinstance(pin, text_type):
pin = pin.encode('utf8')
buf = create_string_buffer(pin)
tries = c_int(-1)
rc = ykpiv.ykpiv_verify(self._state, buf, byref(tries))
if rc == YKPIV.WRONG_PIN:
if tries.value == 0:
self._pin_blocked = True
self._cmd._pin = None
raise WrongPinError(tries.value)
check(rc)
self._cmd._pin = pin
def set_pin(self, pin):
if isinstance(pin, text_type):
pin = pin.encode('utf8')
if len(pin) > 8:
raise ValueError(m.pin_too_long)
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.change_pin(pin)
finally:
self._reset()
def reset_pin(self, puk, new_pin):
if isinstance(new_pin, text_type):
new_pin = new_pin.encode('utf8')
if len(new_pin) > 8:
raise ValueError(m.pin_too_long)
if isinstance(puk, text_type):
puk = puk.encode('utf8')
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.reset_pin(puk, new_pin)
except ValueError as e:
wrap_puk_error(e)
finally:
self._reset()
self._read_status()
def set_puk(self, puk, new_puk):
if isinstance(puk, text_type):
puk = puk.encode('utf8')
if isinstance(new_puk, text_type):
new_puk = new_puk.encode('utf8')
if len(new_puk) > 8:
raise ValueError(m.puk_too_long)
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.change_puk(puk, new_puk)
except ValueError as e:
wrap_puk_error(e)
finally:
self._reset()
def reset_device(self):
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.run('-a', 'reset')
finally:
del self._cmd
def fetch_object(self, object_id):
buf = (c_ubyte * 4096)()
buf_len = c_size_t(sizeof(buf))
check(ykpiv.ykpiv_fetch_object(self._state, object_id, buf,
byref(buf_len)))
return b''.join(map(int2byte, buf[:buf_len.value]))
def save_object(self, object_id, data):
c_data = (c_ubyte * len(data)).from_buffer_copy(data)
check(ykpiv.ykpiv_save_object(self._state, object_id, c_data,
len(data)))
def generate(self, slot, algorithm, pin_policy, touch_policy):
try:
check(ykpiv.ykpiv_disconnect(self._state))
return self._cmd.generate(slot, algorithm, pin_policy, touch_policy)
finally:
self._reset()
def create_csr(self, subject, pubkey_pem, slot):
try:
check(ykpiv.ykpiv_disconnect(self._state))
return self._cmd.create_csr(subject, pubkey_pem, slot)
finally:
self._reset()
def create_selfsigned_cert(self, subject, pubkey_pem, slot, valid_days=365):
try:
check(ykpiv.ykpiv_disconnect(self._state))
return self._cmd.create_ssc(subject, pubkey_pem, slot, valid_days)
finally:
self._reset()
def import_cert(self, cert_pem, slot, frmt='PEM', password=None):
try:
check(ykpiv.ykpiv_disconnect(self._state))
return self._cmd.import_cert(cert_pem, slot, frmt, password)
finally:
self._reset()
self._read_status()
def import_key(self, cert_pem, slot, frmt, password, pin_policy,
touch_policy):
try:
check(ykpiv.ykpiv_disconnect(self._state))
return self._cmd.import_key(cert_pem, slot, frmt, password,
pin_policy, touch_policy)
finally:
self._reset()
def sign_data(self, slot, hashed, algorithm=YKPIV.ALGO.RSA2048):
c_hashed = (c_ubyte * len(hashed)).from_buffer_copy(hashed)
buf = (c_ubyte * 4096)()
buf_len = c_size_t(sizeof(buf))
check(ykpiv.ykpiv_sign_data(self._state, c_hashed, len(hashed), buf,
byref(buf_len), algorithm, int(slot, 16)))
return ''.join(map(int2byte, buf[:buf_len.value]))
def read_cert(self, slot):
try:
data = self.fetch_object(CERT_SLOTS[slot])
except PivError:
return None
cert, rest = der_read(data, 0x70)
zipped, rest = der_read(rest, 0x71)
if zipped != b'\0':
pass # TODO: cert is compressed, uncompress.
return cert
def delete_cert(self, slot):
if slot not in self._certs:
raise ValueError('No certificate loaded in slot: %s' % slot)
try:
check(ykpiv.ykpiv_disconnect(self._state))
self._cmd.delete_cert(slot)
del self._certs[slot]
finally:
self._reset() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/piv.py | piv.py |
organization = "Yubico"
domain = "yubico.com"
app_name = "YubiKey PIV Manager"
win_title_1 = "YubiKey PIV Manager (%s)"
about_1 = "About: %s"
copyright = "Copyright © Yubico"
libraries = "Library versions"
version_1 = "Version: %s"
menu_file = "&File"
menu_help = "&Help"
action_about = "&About"
action_settings = "&Settings"
settings = "Settings"
general = "General"
misc = "Miscellaneous"
certificates = "Certificates"
active_directory = "Active Directory"
active_directory_desc = "The following options are used when requesting a " \
"certificate from the Windows CA"
reader_name = "Card reader name"
no = "no"
ok = "OK"
cancel = "Cancel"
error = "Error"
refresh = "Refresh"
no_key = "No YubiKey found. Please insert a PIV enabled YubiKey..."
key_with_applet_1 = "YubiKey present with applet version: %s."
name = "Name"
name_1 = "Name: %s"
wait = "Please wait..."
device_unplugged = "Unable to communicate with the device, has it been removed?"
certs_loaded_1 = "You have %s certificate(s) loaded."
change_name = "Change name"
change_name_desc = "Change the name of the device."
current_pin_label = "Current PIN:"
current_puk_label = "Current PUK:"
current_key_label = "Current Management Key:"
new_pin_label = "New PIN (6-8 characters):"
new_key_label = "New Management Key:"
verify_pin_label = "Repeat new PIN:"
pin = "PIN"
pin_label = "PIN:"
pin_days_left_1 = "PIN expires in %s days."
puk = "PUK"
puk_label = "PUK:"
new_puk_label = "PUK (6-8 characters):"
verify_puk_label = "Repeat PUK:"
puk_confirm_mismatch = "PUKs don't match!"
no_puk = "No PUK set"
no_puk_warning = "If you do not set a PUK you will not be able to reset your " \
"PIN in case it is ever lost. Continue without setting a PUK?"
puk_not_complex = "PUK doesn't meet complexity rules"
initialize = "Device Initialization"
key_type_pin = "PIN (same as above)"
key_type_key = "Key"
key_invalid = "Invalid management key"
key_invalid_desc = "The key you have provided is invalid. It should contain " \
"exactly 48 hexadecimal characters."
management_key = "Management key"
key_type_label = "Key type:"
key_label = "Management Key:"
use_pin_as_key = "Use PIN as key"
use_separate_key = "Use a separate key"
randomize = "Randomize"
copy_clipboard = "Copy to clipboard"
change_pin = "Change PIN"
reset_pin = "Reset PIN"
reset_device = "Reset device"
reset_device_warning = "This will erase all data including keys and " \
"certificates from the device. Your PIN, PUK and Management Key will be " \
"reset to the factory defaults."
resetting_device = "Resetting device..."
device_resetted = "Device reset complete"
device_resetted_desc = "Your device has now been reset, and will require " \
"initialization."
change_puk = "Change PUK"
change_key = "Change Management Key"
change_pin_desc = "Change your PIN"
change_pin_forced_desc = "Your PIN has expired and must now be changed."
changing_pin = "Setting PIN..."
changing_puk = "Setting PUK..."
changing_key = "Setting Management Key..."
initializing = "Initializing..."
pin_changed = "PIN changed"
pin_changed_desc = "Your PIN has been successfully changed."
puk_changed = "PUK changed"
puk_changed_desc = "Your PUK has been successfully changed."
key_changed = "Management key changed"
key_changed_desc = "Your management key has been successfully changed."
pin_not_changed = "PIN not changed"
pin_not_changed_desc = "New PIN must be different from old PIN"
puk_not_changed = "PUK not changed"
puk_not_changed_desc = "New PUK must be different from old PUK"
pin_puk_same = "PIN and PUK the same"
pin_puk_same_desc = "PIN and PUK must be different"
puk_blocked = "PUK is blocked."
block_puk = "PUK will be blocked"
block_puk_desc = "Using your PIN as Management Key will block your PUK. " \
"You will not be able to recover your PIN if it is lost. A blocked PUK " \
"cannot be unblocked, even by setting a new Management Key."
pin_confirm_mismatch = "PINs don't match!"
pin_empty = "PIN is empty"
pin_not_complex = "PIN doesn't meet complexity rules"
pin_complexity_desc = """Your PIN/PUK must:
* Not contain all or part of the user's account name
* Be at least six characters in length
* Contain characters from three of the following four categories:
* English uppercase characters (A through Z)
* English lowercase characters (a through z)
* Base 10 digits (0 through 9)
* Nonalphanumeric characters (e.g., !, $, #, %)
"""
enter_pin = "Enter PIN"
enter_key = "Enter management key"
manage_pin = "Manage device PINs"
pin_is_key = "PIN is management key."
enter_file_password = "Enter password to unlock file."
password_label = "Password:"
unknown = "Unknown"
change_cert = "Request certificate"
change_cert_warning_1 = "This will generate a new private key and request a " \
"certificate from the Windows CA, overwriting any previously stored " \
"credential in slot '%s' of your YubiKey's PIV applet. This action " \
"cannot be undone."
changing_cert = "Requesting certificate..."
export_to_file = "Export certificate..."
export_cert = "Export certificate"
save_pk = "Save Public Key as..."
save_csr = "Save Certificate Signing Request as..."
generate_key = "Generate new key..."
generate_key_warning_1 = "A new private key will be generated and stored in " \
"slot '%s'."
generating_key = "Generating new key..."
generated_key = "New key generated"
generated_key_desc_1 = "A new private key has been generated in slot '%s'."
gen_out_pk_1 = "The corresponding public key has been saved to:\n%s"
gen_out_csr_1 = "A certificate signing request has been saved to:\n%s"
gen_out_ssc = "A self-signed certificate has been loaded."
gen_out_ca = "A certificate from the CA has been loaded."
import_from_file = "Import from file..."
import_from_file_warning_1 = "Anything currently in slot '%s' will be " \
"overwritten by the imported content. This action cannot be undone."
importing_file = "Importing from file..."
unsupported_file = "Unsupported file type"
delete_cert = "Delete certificate"
delete_cert_warning_1 = "This will delete the certificate and key stored in " \
"slot '%s' of your YubiKey, and cannot be undone."
deleting_cert = "Deleting certificate..."
cert_exported = "Certificate exported"
cert_exported_desc_1 = "Certificate exported to file: %s"
cert_deleted = "Certificate deleted"
cert_deleted_desc = "Certificate deleted successfully"
cert_not_loaded = "No certificate loaded."
cert_expires_1 = "Certificate expires: %s"
cert_installed = "Certificate installed"
cert_installed_desc = "A new certificate has been installed. You may need to " \
"unplug and re-insert your YubiKey before it can be used."
cert_tmpl = "Certificate Template"
subject = "Subject"
error = "Error"
wrong_key = "Incorrect management key"
communication_error = "Communication error with the device"
ykpiv_error_2 = "YkPiv error %d: %s"
wrong_pin_tries_1 = "PIN verification failed. %d tries remaining"
wrong_puk_tries_1 = "PUK verification failed. %d tries remaining"
pin_blocked = "Your PIN has been blocked due to too many incorrect attempts."
pin_too_long = "PIN must be no more than 8 characters long.\n" \
"NOTE: Special characters may be counted more than once."
puk_too_long = "PUK must be no more than 8 characters long.\n" \
"NOTE: Special characters may be counted more than once."
certreq_error = "There was an error requesting a certificate."
certreq_error_1 = "Error running certreq: %s"
ca_not_connected = "You currently do not have a connection to a " \
"Certification Authority."
authentication_error = "Unable to authenticate to device"
use_complex_pins = "Enforce complex PIN/PUKs"
pin_expires = "Force periodic PIN change"
pin_expires_days = "How often (days)?"
issued_to_label = "Issued to:"
issued_by_label = "Issued by:"
valid_from_label = "Valid from:"
valid_to_label = "Valid to:"
usage_9a = "The X.509 Certificate for PIV Authentication and its associated " \
"private key, as defined in FIPS 201, is used to authenticate the card " \
"and the cardholder."
usage_9c = "The X.509 Certificate for Digital Signature and its associated " \
"private key, as defined in FIPS 201, support the use of digital " \
"signatures for the purpose of document signing. "
usage_9d = "The X.509 Certificate for Key Management and its associated " \
"private key, as defined in FIPS 201, support the use of encryption for " \
"the purpose of confidentiality."
usage_9e = "FIPS 201 specifies the optional Card Authentication Key (CAK) as " \
"an asymmetric or symmetric key that is used to support additional " \
"physical access applications. "
algorithm = "Algorithm"
alg_rsa_1024 = "RSA (1024 bits)"
alg_rsa_2048 = "RSA (2048 bits)"
alg_ecc_p256 = "ECC (P-256)"
alg_ecc_p384 = "ECC (P-384)"
algorithm_1 = "Algorithm: %s"
output = "Output"
out_pk = "Public key"
out_csr = "Certificate Signing Request (CSR)"
out_ssc = "Create a self-signed certificate"
out_ca = "Request a certificate from a Windows CA"
no_output = "Your configuration does not allow any valid output format."
invalid_subject = "Invalid subject"
invalid_subject_desc = """The subject must be written as:
/CN=host.example.com/OU=test/O=example.com"""
usage_policy = "Usage policy"
pin_policy = "Require PIN"
pin_policy_1 = "Require PIN: %s"
pin_policy_default = "Slot default"
pin_policy_never = "Never"
pin_policy_once = "Once"
pin_policy_always = "Always"
touch_policy = "Require button touch"
touch_needed = "User action needed"
touch_needed_desc = "You have chosen to require user interaction to use this " \
"certificate. Once you close this dialog, the light on your YubiKey " \
"will start slowly blinking. At that point please touch the button on " \
"your YubiKey."
touch_prompt = "Touch the button now..."
expiration_date = "Expiration date"
setting_up_macos = "Setting up for macOS..."
macos_pairing_title = "Set Up YubiKey for macOS"
macos_pairing_desc = "<p>This version of macOS allows you to pair your " \
"YubiKey with your user account. When you have completed the pairing, " \
"you can use your YubiKey to log in to your Mac.</p><p>" \
"Do you want to generate certificates for this purpose (recommended)?</p>"
setup_for_macos = "Setup for macOS"
setup_macos_compl = "Setup for macOS completed"
setup_macos_compl_desc = "Your YubiKey is now ready to be paired with your " \
"user account. To start the pairing process, remove and re-insert " \
"your YubiKey."
non_numeric_pin_warning = "For cross-platform compatibility, " \
"we recommend " \
"you enter a PIN of 6-8 numeric digits."
non_numeric_pin = "Pairing your YubiKey with macOS requires your PIN to only "\
"contain numeric characters. Do you want to change your PIN?"
overwrite_slot_warning = "Overwrite slot?"
overwrite_slot_warning_desc = "This will overwrite all data currently " \
"stored in slot '%s'. This action cannot be undone. " \
"Do you want to continue?"
overwrite_slot_warning_macos = "This will overwrite all data currently " \
"stored in slot '9a' and '9d'. This action cannot be undone. "\
"Do you want to continue?"
not_default_pin = "Your credentials for the YubiKey are not the default " \
"values. This may occur when the PIN or PUK has been changed with a " \
"different tool. Use the 'Manage device PINs' option to change the " \
"credentials." | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/messages.py | messages.py |
from __future__ import absolute_import
from PySide import QtCore
from collections import MutableMapping
__all__ = ['Settings', 'PySettings', 'convert_to']
def convert_to(value, target_type):
if target_type is list:
return [] if value is None else [value]
if target_type is int:
return 0 if value in ['', 'false', 'False'] else int(value)
if target_type is float:
return float(value)
if target_type is bool:
return value not in ['', 'false', 'False']
return value
class SettingsGroup(object):
def __init__(self, settings, mutex, group):
self._settings = settings
self._mutex = mutex
self._group = group
def __getattr__(self, method_name):
if hasattr(self._settings, method_name):
fn = getattr(self._settings, method_name)
def wrapped(*args, **kwargs):
try:
self._mutex.lock()
self._settings.beginGroup(self._group)
return fn(*args, **kwargs)
finally:
self._settings.endGroup()
self._mutex.unlock()
return wrapped
def rename(self, new_name):
data = dict((key, self.value(key)) for key in self.childKeys())
self.remove('')
self._group = new_name
for k, v in data.items():
self.setValue(k, v)
def __repr__(self):
return 'Group(%s)' % self._group
class Settings(QtCore.QObject):
def __init__(self, q_settings, wrap=True):
super(Settings, self).__init__()
self._mutex = QtCore.QMutex(QtCore.QMutex.Recursive)
self._wrap = wrap
self._q_settings = q_settings
def get_group(self, group):
g = SettingsGroup(self._q_settings, self._mutex, group)
if self._wrap:
g = PySettings(g)
return g
@staticmethod
def wrap(*args, **kwargs):
return Settings(QtCore.QSettings(*args, **kwargs))
class PySettings(MutableMapping):
def __init__(self, settings):
self._settings = settings
def __getattr__(self, method_name):
return getattr(self._settings, method_name)
def get(self, key, default=None):
val = self._settings.value(key, default)
if not isinstance(val, type(default)):
val = convert_to(val, type(default))
return val
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
self._settings.setValue(key, value)
def __delitem__(self, key):
self._settings.remove(key)
def __iter__(self):
for key in list(self.keys()):
yield key
def __len__(self):
return len(self._settings.childKeys())
def __contains__(self, key):
return self._settings.contains(key)
def keys(self):
return self._settings.childKeys()
def update(self, data):
for key, value in list(data.items()):
self[key] = value
def clear(self):
self._settings.remove('')
def __repr__(self):
return 'PySettings(%s)' % self._settings | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/qt/settings.py | settings.py |
from __future__ import absolute_import
from PySide import QtGui, QtCore
from .worker import Worker
import os
import sys
import importlib
from .. import compat
__all__ = ['Application', 'Dialog', 'MutexLocker']
TOP_SECTION = '<b>%s</b>'
SECTION = '<br><b>%s</b>'
class Dialog(QtGui.QDialog):
def __init__(self, *args, **kwargs):
super(Dialog, self).__init__(*args, **kwargs)
self.setWindowFlags(self.windowFlags() ^
QtCore.Qt.WindowContextHelpButtonHint)
self._headers = _Headers()
@property
def headers(self):
return self._headers
def section(self, title):
return self._headers.section(title)
class _Headers(object):
def __init__(self):
self._first = True
def section(self, title):
if self._first:
self._first = False
section = TOP_SECTION % title
else:
section = SECTION % title
return QtGui.QLabel(section)
class _MainWindow(QtGui.QMainWindow):
def __init__(self):
super(_MainWindow, self).__init__()
self._widget = None
def hide(self):
if sys.platform == 'darwin':
from .osx import app_services
app_services.osx_hide()
else:
super(_MainWindow, self).hide()
def customEvent(self, event):
event.callback()
event.accept()
class Application(QtGui.QApplication):
_quit = False
def __init__(self, m=None, version=None):
super(Application, self).__init__(sys.argv)
self._determine_basedir()
self._read_package_version(version)
self.window = _MainWindow()
if m: # Run all strings through Qt translation
for key in dir(m):
if (isinstance(key, compat.string_types) and
not key.startswith('_')):
setattr(m, key, self.tr(getattr(m, key)))
self.worker = Worker(self.window, m)
def _determine_basedir(self):
if getattr(sys, 'frozen', False):
# we are running in a PyInstaller bundle
self.basedir = sys._MEIPASS
else:
# we are running in a normal Python environment
top_module_str = __package__.split('.')[0]
top_module = importlib.import_module(top_module_str)
self.basedir = os.path.dirname(top_module.__file__)
def _read_package_version(self, version):
if version is None:
return
pversion_fn = os.path.join(self.basedir, 'package_version.txt')
try:
with open(pversion_fn, 'r') as f:
pversion = int(f.read().strip())
except:
pversion = 0
if pversion > 0:
version += '.%d' % pversion
self.version = version
def ensure_singleton(self, name=None):
if not name:
name = self.applicationName()
from PySide import QtNetwork
self._l_socket = QtNetwork.QLocalSocket()
self._l_socket.connectToServer(name, QtCore.QIODevice.WriteOnly)
if self._l_socket.waitForConnected():
self._stop()
sys.exit(0)
else:
self._l_server = QtNetwork.QLocalServer()
if not self._l_server.listen(name):
QtNetwork.QLocalServer.removeServer(name)
self._l_server.listen(name)
self._l_server.newConnection.connect(self._show_window)
def _show_window(self):
self.window.show()
self.window.activateWindow()
def quit(self):
super(Application, self).quit()
self._quit = True
def _stop(self):
worker_thread = self.worker.thread()
worker_thread.quit()
worker_thread.wait()
self.deleteLater()
sys.stdout.flush()
sys.stderr.flush()
def exec_(self):
if not self._quit:
status = super(Application, self).exec_()
else:
status = 0
self._stop()
return status
class MutexLocker(object):
"""Drop-in replacement for QMutexLocker that can start unlocked."""
def __init__(self, mutex, lock=True):
self._mutex = mutex
self._locked = False
if lock:
self.relock()
def lock(self, try_lock=False):
if try_lock:
self._locked = self._mutex.tryLock()
else:
self._mutex.lock()
self._locked = True
return self._locked and self or None
def relock(self):
self.lock()
def unlock(self):
if self._locked:
self._mutex.unlock()
def __del__(self):
self.unlock() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/qt/classes.py | classes.py |
from __future__ import absolute_import
from PySide import QtCore, QtGui
from functools import wraps
from inspect import getargspec
__all__ = ['get_text', 'get_active_window', 'is_minimized', 'connect_once']
class _DefaultMessages(object):
def __init__(self, default_m, m=None):
self._defaults = default_m
self._m = m
def __getattr__(self, method_name):
if hasattr(self._m, method_name):
return getattr(self._m, method_name)
else:
return getattr(self._defaults, method_name)
def default_messages(_m, name='m'):
def inner(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
index = getargspec(fn).args.index(name)
if len(args) > index:
args = list(args)
args[index] = _DefaultMessages(_m, args[index])
else:
kwargs[name] = _DefaultMessages(_m, kwargs.get(name))
return fn(*args, **kwargs)
return wrapper
return inner
def get_text(*args, **kwargs):
flags = (
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowSystemMenuHint
)
kwargs['flags'] = flags
return QtGui.QInputDialog.getText(*args, **kwargs)
def get_active_window():
active_win = QtGui.QApplication.activeWindow()
if active_win is not None:
return active_win
wins = [w for w in QtGui.QApplication.topLevelWidgets()
if isinstance(w, QtGui.QDialog) and w.isVisible()]
if not wins:
return QtCore.QCoreApplication.instance().window
return wins[0] # TODO: If more than one candidates remain, find best one.
def connect_once(signal, slot):
_SignalConnector(signal, slot)
def is_minimized(window):
"""Returns True iff the window is minimized or has been sent to the tray"""
return not window.isVisible() or window.isMinimized()
class _SignalConnector(QtCore.QObject):
_instances = set()
def __init__(self, signal, slot):
super(_SignalConnector, self).__init__()
self.signal = signal
self.slot = slot
self._instances.add(self)
self.signal.connect(self.wrappedSlot)
def wrappedSlot(self, *args, **kwargs):
self._instances.discard(self)
self.signal.disconnect(self.wrappedSlot)
self.slot(*args, **kwargs) | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/qt/utils.py | utils.py |
from __future__ import absolute_import
from PySide import QtGui, QtCore
from functools import partial
from os import getenv
from .utils import connect_once, get_active_window, default_messages
import traceback
class _Messages(object):
wait = 'Please wait...'
class _Event(QtCore.QEvent):
EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())
def __init__(self, callback):
super(_Event, self).__init__(_Event.EVENT_TYPE)
self._callback = callback
def callback(self):
self._callback()
del self._callback
class Worker(QtCore.QObject):
_work_signal = QtCore.Signal(tuple)
_work_done_0 = QtCore.Signal()
@default_messages(_Messages)
def __init__(self, window, m):
super(Worker, self).__init__()
self.m = m
self.window = window
self._work_signal.connect(self.work)
self.work_thread = QtCore.QThread()
self.moveToThread(self.work_thread)
self.work_thread.start()
def post(self, title, fn, callback=None, return_errors=False):
busy = QtGui.QProgressDialog(title, None, 0, 0, get_active_window())
busy.setWindowTitle(self.m.wait)
busy.setWindowModality(QtCore.Qt.WindowModal)
busy.setMinimumDuration(0)
busy.setWindowFlags(
busy.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)
busy.show()
connect_once(self._work_done_0, busy.close)
self.post_bg(fn, callback, return_errors)
def post_bg(self, fn, callback=None, return_errors=False):
if isinstance(fn, tuple):
fn = partial(fn[0], *fn[1:])
self._work_signal.emit((fn, callback, return_errors))
def post_fg(self, fn):
if isinstance(fn, tuple):
fn = partial(fn[0], *fn[1:])
event = _Event(fn)
QtGui.QApplication.postEvent(self.window, event)
@QtCore.Slot(tuple)
def work(self, job):
QtCore.QThread.msleep(10) # Needed to yield
(fn, callback, return_errors) = job
try:
result = fn()
except Exception as e:
result = e
if getenv('DEBUG'):
traceback.print_exc()
if not return_errors:
def callback(e): raise e
if callback:
event = _Event(partial(callback, result))
QtGui.QApplication.postEvent(self.window, event)
self._work_done_0.emit() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/qt/worker.py | worker.py |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import json
import errno
import pkg_resources
from glob import glob
VS_VERSION_INFO = """
VSVersionInfo(
ffi=FixedFileInfo(
# filevers and prodvers should be always a tuple with four
# items: (1, 2, 3, 4)
# Set not needed items to zero 0.
filevers=%(ver_tup)r,
prodvers=%(ver_tup)r,
# Contains a bitmask that specifies the valid bits 'flags'r
mask=0x0,
# Contains a bitmask that specifies the Boolean attributes
# of the file.
flags=0x0,
# The operating system for which this file was designed.
# 0x4 - NT and there is no need to change it.
OS=0x4,
# The general type of file.
# 0x1 - the file is an application.
fileType=0x1,
# The function of the file.
# 0x0 - the function is not defined for this fileType
subtype=0x0,
# Creation date and time stamp.
date=(0, 0)
),
kids=[
StringFileInfo(
[
StringTable(
u'040904E4',
[StringStruct(u'FileDescription', u'%(name)s'),
StringStruct(u'FileVersion', u'%(ver_str)s'),
StringStruct(u'InternalName', u'%(internal_name)s'),
StringStruct(u'LegalCopyright', u'Copyright © 2015 Yubico'),
StringStruct(u'OriginalFilename', u'%(exe_name)s'),
StringStruct(u'ProductName', u'%(name)s'),
StringStruct(u'ProductVersion', u'%(ver_str)s')])
]),
VarFileInfo([VarStruct(u'Translation', [1033, 1252])])
]
)"""
data = json.loads(os.environ['pyinstaller_data'])
try:
data = dict((k, v.encode('ascii') if getattr(v, 'encode', None) else v)
for k, v in data.items())
except NameError:
pass # Python 3, encode not needed.
dist = pkg_resources.get_distribution(data['name'])
DEBUG = bool(data['debug'])
NAME = data['long_name']
WIN = sys.platform in ['win32', 'cygwin']
OSX = sys.platform in ['darwin']
ver_str = dist.version
if data['package_version'] > 0:
ver_str += '.%d' % data['package_version']
file_ext = '.exe' if WIN else ''
if WIN:
icon_ext = 'ico'
elif OSX:
icon_ext = 'icns'
else:
icon_ext = 'png'
ICON = os.path.join('resources', '%s.%s' % (data['name'], icon_ext))
if not os.path.isfile(ICON):
ICON = None
# Generate scripts from entry_points.
merge = []
entry_map = dist.get_entry_map()
console_scripts = entry_map.get('console_scripts', {})
gui_scripts = entry_map.get('gui_scripts', {})
for ep in list(gui_scripts.values()) + list(console_scripts.values()):
script_path = os.path.join(os.getcwd(), ep.name + '-script.py')
with open(script_path, 'w') as fh:
fh.write("import %s\n" % ep.module_name)
fh.write("%s.%s()\n" % (ep.module_name, '.'.join(ep.attrs)))
merge.append(
(Analysis([script_path], [dist.location], None, None, None, None),
ep.name, ep.name + file_ext)
)
MERGE(*merge)
# Read version information on Windows.
VERSION = None
if WIN:
VERSION = 'build/file_version_info.txt'
global int_or_zero # Needed due to how this script is invoked
def int_or_zero(v):
try:
return int(v)
except ValueError:
return 0
ver_tup = tuple(int_or_zero(v) for v in ver_str.split('.'))
# Windows needs 4-tuple.
if len(ver_tup) < 4:
ver_tup += (0,) * (4-len(ver_tup))
elif len(ver_tup) > 4:
ver_tup = ver_tup[:4]
# Write version info.
with open(VERSION, 'w') as f:
f.write(VS_VERSION_INFO % {
'name': NAME,
'internal_name': data['name'],
'ver_tup': ver_tup,
'ver_str': ver_str,
'exe_name': data['name'] + file_ext
})
pyzs = [PYZ(m[0].pure) for m in merge]
exes = []
for (a, a_name, a_name_ext), pyz in zip(merge, pyzs):
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name=a_name_ext,
debug=DEBUG,
strip=None,
upx=True,
console=DEBUG or a_name in console_scripts,
append_pkg=not OSX,
version=VERSION,
icon=ICON)
exes.append(exe)
# Sign the executable
if WIN:
os.system("signtool.exe sign /fd SHA256 /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" %
(exe.name))
collect = []
for (a, _, a_name), exe in zip(merge, exes):
collect += [exe, a.binaries, a.zipfiles, a.datas]
# Data files
collect.append([(os.path.basename(fn), fn, 'DATA') for fn in data['data_files']])
# DLLs, dylibs and executables should go here.
collect.append([(fn[4:], fn, 'BINARY') for fn in glob('lib/*')])
coll = COLLECT(*collect, strip=None, upx=True, name=NAME)
# Write package version for app to display
pversion_fn = os.path.join('dist', NAME, 'package_version.txt')
with open(pversion_fn, 'w') as f:
f.write(str(data['package_version']))
# Create .app for OSX
if OSX:
app = BUNDLE(coll,
name="%s.app" % NAME,
version=ver_str,
icon=ICON)
qt_conf = 'dist/%s.app/Contents/Resources/qt.conf' % NAME
qt_conf_dir = os.path.dirname(qt_conf)
try:
os.makedirs(qt_conf_dir)
except OSError as e:
if not (e.errno == errno.EEXIST and os.path.isdir(qt_conf_dir)):
raise
with open(qt_conf, 'w') as f:
f.write('[Path]\nPlugins = plugins')
# Create Windows installer
if WIN:
installer_cfg = 'resources/win-installer.nsi'
if os.path.isfile(installer_cfg):
os.system('makensis.exe -D"VERSION=%s" %s' % (ver_str, installer_cfg))
installer = "dist/%s-%s-win.exe" % (data['name'], ver_str)
os.system("signtool.exe sign /fd SHA256 /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" %
(installer))
print("Installer created: %s" % installer) | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/setup/pyinstaller_spec.py | pyinstaller_spec.py |
from __future__ import absolute_import
__dependencies__ = []
__all__ = ['get_version', 'setup', 'release']
from setuptools import setup as _setup, find_packages, Command
from setuptools.command.sdist import sdist
from distutils import log
from distutils.errors import DistutilsSetupError
from datetime import date
from glob import glob
import os
import re
VERSION_PATTERN = re.compile(r"(?m)^__version__\s*=\s*['\"](.+)['\"]$")
DEPENDENCY_PATTERN = re.compile(
r"(?m)__dependencies__\s*=\s*\[((['\"].+['\"]\s*(,\s*)?)+)\]")
YC_DEPENDENCY_PATTERN = re.compile(
r"(?m)__yc_dependencies__\s*=\s*\[((['\"].+['\"]\s*(,\s*)?)+)\]")
base_module = __name__.rsplit('.', 1)[0]
def get_version(module_name_or_file=None):
"""Return the current version as defined by the given module/file."""
if module_name_or_file is None:
parts = base_module.split('.')
module_name_or_file = parts[0] if len(parts) > 1 else \
find_packages(exclude=['test', 'test.*'])[0]
if os.path.isdir(module_name_or_file):
module_name_or_file = os.path.join(module_name_or_file, '__init__.py')
with open(module_name_or_file, 'r') as f:
match = VERSION_PATTERN.search(f.read())
return match.group(1)
def get_dependencies(module):
basedir = os.path.dirname(__file__)
fn = os.path.join(basedir, module + '.py')
if os.path.isfile(fn):
with open(fn, 'r') as f:
match = DEPENDENCY_PATTERN.search(f.read())
if match:
return [s.strip().strip('"\'')
for s in match.group(1).split(',')]
return []
def get_yc_dependencies(module):
basedir = os.path.dirname(__file__)
fn = os.path.join(basedir, module + '.py')
if os.path.isfile(fn):
with open(fn, 'r') as f:
match = YC_DEPENDENCY_PATTERN.search(f.read())
if match:
return [s.strip().strip('"\'')
for s in match.group(1).split(',')]
return []
def get_package(module):
return base_module + '.' + module
def setup(**kwargs):
# TODO: Find a better way to pass this to a command.
os.environ['setup_long_name'] = kwargs.pop('long_name', kwargs.get('name'))
if 'version' not in kwargs:
kwargs['version'] = get_version()
packages = kwargs.setdefault(
'packages',
find_packages(exclude=['test', 'test.*', base_module + '.*']))
packages.append(__name__)
install_requires = kwargs.setdefault('install_requires', [])
yc_blacklist = kwargs.pop('yc_requires_exclude', [])
yc_requires = kwargs.pop('yc_requires', [])
yc_requires_stack = yc_requires[:]
while yc_requires_stack:
yc_module = yc_requires_stack.pop()
for yc_dep in get_yc_dependencies(yc_module):
if yc_dep not in yc_requires:
yc_requires.append(yc_dep)
yc_requires_stack.append(yc_dep)
for yc_module in yc_requires:
packages.append(get_package(yc_module))
for dep in get_dependencies(yc_module):
if dep not in install_requires and dep not in yc_blacklist:
install_requires.append(dep)
cmdclass = kwargs.setdefault('cmdclass', {})
cmdclass.setdefault('release', release)
cmdclass.setdefault('build_man', build_man)
cmdclass.setdefault('sdist', custom_sdist)
return _setup(**kwargs)
class custom_sdist(sdist):
def run(self):
self.run_command('build_man')
# Run if available:
if 'qt_resources' in self.distribution.cmdclass:
self.run_command('qt_resources')
sdist.run(self)
class build_man(Command):
description = "create man pages from asciidoc source"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
self.cwd = os.getcwd()
self.fullname = self.distribution.get_fullname()
self.name = self.distribution.get_name()
self.version = self.distribution.get_version()
def run(self):
if os.getcwd() != self.cwd:
raise DistutilsSetupError("Must be in package root!")
for fname in glob(os.path.join('man', '*.adoc')):
self.announce("Converting: " + fname, log.INFO)
self.execute(os.system,
('a2x -d manpage -f manpage "%s"' % fname,))
class release(Command):
description = "create and release a new version"
user_options = [
('keyid', None, "GPG key to sign with"),
('skip-tests', None, "skip running the tests"),
('pypi', None, "publish to pypi"),
]
boolean_options = ['skip-tests', 'pypi']
def initialize_options(self):
self.keyid = None
self.skip_tests = 0
self.pypi = 0
def finalize_options(self):
self.cwd = os.getcwd()
self.fullname = self.distribution.get_fullname()
self.name = self.distribution.get_name()
self.version = self.distribution.get_version()
def _verify_version(self):
with open('NEWS', 'r') as news_file:
line = news_file.readline()
now = date.today().strftime('%Y-%m-%d')
if not re.search(r'Version %s \(released %s\)' % (self.version, now),
line):
raise DistutilsSetupError("Incorrect date/version in NEWS!")
def _verify_tag(self):
if os.system('git tag | grep -q "^%s\$"' % self.fullname) == 0:
raise DistutilsSetupError(
"Tag '%s' already exists!" % self.fullname)
def _verify_not_dirty(self):
if os.system('git diff --shortstat | grep -q "."') == 0:
raise DistutilsSetupError("Git has uncommitted changes!")
def _sign(self):
if os.path.isfile('dist/%s.tar.gz.asc' % self.fullname):
# Signature exists from upload, re-use it:
sign_opts = ['--output dist/%s.tar.gz.sig' % self.fullname,
'--dearmor dist/%s.tar.gz.asc' % self.fullname]
else:
# No signature, create it:
sign_opts = ['--detach-sign', 'dist/%s.tar.gz' % self.fullname]
if self.keyid:
sign_opts.insert(1, '--default-key ' + self.keyid)
self.execute(os.system, ('gpg ' + (' '.join(sign_opts)),))
if os.system('gpg --verify dist/%s.tar.gz.sig' % self.fullname) != 0:
raise DistutilsSetupError("Error verifying signature!")
def _tag(self):
tag_opts = ['-s', '-m ' + self.fullname, self.fullname]
if self.keyid:
tag_opts[0] = '-u ' + self.keyid
self.execute(os.system, ('git tag ' + (' '.join(tag_opts)),))
def run(self):
if os.getcwd() != self.cwd:
raise DistutilsSetupError("Must be in package root!")
self._verify_version()
self._verify_tag()
self._verify_not_dirty()
self.run_command('check')
self.execute(os.system, ('git2cl > ChangeLog',))
self.run_command('sdist')
if not self.skip_tests:
try:
self.run_command('test')
except SystemExit as e:
if e.code != 0:
raise DistutilsSetupError("There were test failures!")
if self.pypi:
cmd_obj = self.distribution.get_command_obj('upload')
cmd_obj.sign = True
if self.keyid:
cmd_obj.identity = self.keyid
self.run_command('upload')
self._sign()
self._tag()
self.announce("Release complete! Don't forget to:", log.INFO)
self.announce("")
self.announce(" git push && git push --tags", log.INFO)
self.announce("") | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/setup/__init__.py | __init__.py |
from __future__ import absolute_import
import os.path
import re
import sys
import glob
import platform
import ctypes
import ctypes.util
def _environ_path(name):
if name in os.environ:
return os.environ[name].split(":")
else:
return []
class LibraryLoader(object):
def __init__(self):
self.other_dirs = []
def load_library(self, libname, version=None):
"""Given the name of a library, load it."""
paths = self.getpaths(libname)
for path in paths:
if os.path.exists(path):
return self.load(path)
raise ImportError("%s not found." % libname)
def load(self, path):
"""Given a path to a library, load it."""
try:
# Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
# of the default RTLD_LOCAL. Without this, you end up with
# libraries not being loadable, resulting in "Symbol not found"
# errors
if sys.platform == 'darwin':
return ctypes.CDLL(path, ctypes.RTLD_GLOBAL)
else:
return ctypes.cdll.LoadLibrary(path)
except OSError as e:
raise ImportError(e)
def getpaths(self, libname):
"""Return a list of paths where the library might be found."""
if os.path.isabs(libname):
yield libname
else:
# FIXME / TODO return '.' and os.path.dirname(__file__)
for path in self.getplatformpaths(libname):
yield path
path = ctypes.util.find_library(libname)
if path:
yield path
def getplatformpaths(self, libname):
return []
# Darwin (Mac OS X)
class DarwinLibraryLoader(LibraryLoader):
name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
"%s.so", "%s.bundle", "%s"]
def getplatformpaths(self, libname):
if os.path.pathsep in libname:
names = [libname]
else:
names = [format % libname for format in self.name_formats]
for dir in self.getdirs(libname):
for name in names:
yield os.path.join(dir, name)
def getdirs(self, libname):
'''Implements the dylib search as specified in Apple documentation:
http://developer.apple.com/documentation/DeveloperTools/Conceptual/
DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
Before commencing the standard search, the method first checks
the bundle's ``Frameworks`` directory if the application is running
within a bundle (OS X .app).
'''
dyld_fallback_library_path = _environ_path(
"DYLD_FALLBACK_LIBRARY_PATH")
if not dyld_fallback_library_path:
dyld_fallback_library_path = [os.path.expanduser('~/lib'),
'/usr/local/lib', '/usr/lib']
dirs = []
if '/' in libname:
dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
else:
dirs.extend(_environ_path("LD_LIBRARY_PATH"))
dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
dirs.extend(self.other_dirs)
dirs.append(".")
dirs.append(os.path.dirname(__file__))
if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
dirs.append(os.path.join(
os.environ['RESOURCEPATH'],
'..',
'Frameworks'))
if hasattr(sys, 'frozen'):
dirs.append(sys._MEIPASS)
dirs.extend(dyld_fallback_library_path)
return dirs
# Posix
class PosixLibraryLoader(LibraryLoader):
_ld_so_cache = None
def load_library(self, libname, version=None):
try:
return self.load(ctypes.util.find_library(libname))
except ImportError:
return super(PosixLibraryLoader, self).load_library(
libname, version)
def _create_ld_so_cache(self):
# Recreate search path followed by ld.so. This is going to be
# slow to build, and incorrect (ld.so uses ld.so.cache, which may
# not be up-to-date). Used only as fallback for distros without
# /sbin/ldconfig.
#
# We assume the DT_RPATH and DT_RUNPATH binary sections are omitted.
directories = []
for name in ("LD_LIBRARY_PATH",
"SHLIB_PATH", # HPUX
"LIBPATH", # OS/2, AIX
"LIBRARY_PATH", # BE/OS
):
if name in os.environ:
directories.extend(os.environ[name].split(os.pathsep))
directories.extend(self.other_dirs)
directories.append(".")
directories.append(os.path.dirname(__file__))
try:
directories.extend([dir.strip()
for dir in open('/etc/ld.so.conf')])
except IOError:
pass
unix_lib_dirs_list = ['/lib', '/usr/lib', '/lib64', '/usr/lib64']
if sys.platform.startswith('linux'):
# Try and support multiarch work in Ubuntu
# https://wiki.ubuntu.com/MultiarchSpec
bitage = platform.architecture()[0]
if bitage.startswith('32'):
# Assume Intel/AMD x86 compat
unix_lib_dirs_list += [
'/lib/i386-linux-gnu', '/usr/lib/i386-linux-gnu']
elif bitage.startswith('64'):
# Assume Intel/AMD x86 compat
unix_lib_dirs_list += [
'/lib/x86_64-linux-gnu', '/usr/lib/x86_64-linux-gnu']
else:
# guess...
unix_lib_dirs_list += glob.glob('/lib/*linux-gnu')
directories.extend(unix_lib_dirs_list)
cache = {}
lib_re = re.compile(r'lib(.*)\.s[ol]')
ext_re = re.compile(r'\.s[ol]$')
for dir in directories:
try:
for path in glob.glob("%s/*.s[ol]*" % dir):
file = os.path.basename(path)
# Index by filename
if file not in cache:
cache[file] = path
# Index by library name
match = lib_re.match(file)
if match:
library = match.group(1)
if library not in cache:
cache[library] = path
except OSError:
pass
self._ld_so_cache = cache
def getplatformpaths(self, libname):
if self._ld_so_cache is None:
self._create_ld_so_cache()
result = self._ld_so_cache.get(libname)
if result:
yield result
path = ctypes.util.find_library(libname)
if path:
yield os.path.join("/lib", path)
# Windows
class _WindowsLibrary(object):
def __init__(self, path):
self.cdll = ctypes.cdll.LoadLibrary(path)
self.windll = ctypes.windll.LoadLibrary(path)
def __getattr__(self, name):
try:
return getattr(self.cdll, name)
except AttributeError:
try:
return getattr(self.windll, name)
except AttributeError:
raise
class WindowsLibraryLoader(LibraryLoader):
name_formats = ["%s.dll", "lib%s.dll", "%slib.dll"]
def load_library(self, libname, version=None):
try:
result = LibraryLoader.load_library(self, libname, version)
except ImportError:
result = None
if os.path.sep not in libname:
formats = self.name_formats[:]
if version:
formats.append("lib%%s-%s.dll" % version)
for name in formats:
try:
result = getattr(ctypes.cdll, name % libname)
if result:
break
except WindowsError:
result = None
if result is None:
try:
result = getattr(ctypes.cdll, libname)
except WindowsError:
result = None
if result is None:
raise ImportError("%s not found." % libname)
return result
def load(self, path):
return _WindowsLibrary(path)
def getplatformpaths(self, libname):
if os.path.sep not in libname:
for name in self.name_formats:
dll_in_current_dir = os.path.abspath(name % libname)
if os.path.exists(dll_in_current_dir):
yield dll_in_current_dir
path = ctypes.util.find_library(name % libname)
if path:
yield path
# Platform switching
# If your value of sys.platform does not appear in this dict, please contact
# the Ctypesgen maintainers.
loaderclass = {
"darwin": DarwinLibraryLoader,
"cygwin": WindowsLibraryLoader,
"win32": WindowsLibraryLoader
}
loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
def add_library_search_dirs(other_dirs):
loader.other_dirs = other_dirs
load_library = loader.load_library
del loaderclass | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/yubicommon/ctypes/libloader.py | libloader.py |
from PySide import QtGui, QtCore, QtNetwork
from pivman import messages as m
from pivman.piv import PivError, DeviceGoneError
from pivman.storage import settings, SETTINGS
from pivman.view.utils import Dialog, get_text
from pivman.view.generate_dialog import GenerateKeyDialog
from pivman.view.usage_policy_dialog import UsagePolicyDialog
from datetime import datetime
from functools import partial
SLOTS = {
'9a': 'Authentication',
'9c': 'Digital Signature',
'9d': 'Key Management',
'9e': 'Card Authentication',
}
USAGES = {
'9a': m.usage_9a,
'9c': m.usage_9c,
'9d': m.usage_9d,
'9e': m.usage_9e,
}
FILE_FILTER = 'Certificate/key files ' \
'(*.pfx *.p12 *.cer *.crt *.key *.pem *.der)'
def detect_type(data, fn):
suffix = '.' in fn and fn.lower().rsplit('.', 1)[1]
f_format = None # pfx, pem or der
f_type = 0 # 1 for certificate, 2 for key, 3 for both
needs_password = False
if suffix in ['pfx', 'p12']:
f_format = 'pfx'
needs_password = True
else:
f_format = 'pem' if data.startswith(b'-----') else 'der'
if f_format == 'pem':
if b'CERTIFICATE' in data and b'PRIVATE KEY' in data:
f_type = 3
elif b'PRIVATE KEY' in data:
f_type = 2
elif b'CERTIFICATE' in data:
f_type = 1
needs_password = b'ENCRYPTED' in data
elif suffix in ['cer', 'crt']:
f_type = 1
elif suffix in ['key']:
f_type = 2
else:
certs = QtNetwork.QSslCertificate.fromData(
data, QtNetwork.QSsl.Der)
f_type = 1 if certs else 2
return f_type, f_format, needs_password
def import_file(controller, slot, fn):
with open(fn, 'rb') as f:
data = f.read()
f_type, f_format, needs_password = detect_type(data, fn)
if f_type == 2 and f_format == 'der':
return None, None, False # We don't know what type of key this is.
def func(password=None, pin_policy=None, touch_policy=False):
if f_format == 'pfx':
controller.import_key(data, slot, 'PKCS12', password, pin_policy,
touch_policy)
controller.import_certificate(data, slot, 'PKCS12', password)
elif f_format == 'pem':
if f_type == 1:
controller.import_certificate(data, slot, 'PEM', password)
elif f_type == 2:
controller.import_key(data, slot, 'PEM', password, pin_policy,
touch_policy)
elif f_type == 3:
controller.import_certificate(data, slot, 'PEM', password)
controller.import_key(data, slot, 'PEM', password, pin_policy,
touch_policy)
else:
controller.import_certificate(data, slot, 'DER')
return func, needs_password, f_type != 1
class CertPanel(QtGui.QWidget):
def __init__(self, controller, slot, parent=None):
super(CertPanel, self).__init__(parent)
self._controller = controller
self._slot = slot
controller.use(self._build_ui)
def _build_ui(self, controller):
cert = controller.get_certificate(self._slot)
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
status = QtGui.QGridLayout()
status.addWidget(QtGui.QLabel(m.issued_to_label), 0, 0)
issued_to = cert.subjectInfo(QtNetwork.QSslCertificate.CommonName)
status.addWidget(QtGui.QLabel(issued_to), 0, 1)
status.addWidget(QtGui.QLabel(m.issued_by_label), 0, 2)
issued_by = cert.issuerInfo(QtNetwork.QSslCertificate.CommonName)
status.addWidget(QtGui.QLabel(issued_by), 0, 3)
status.addWidget(QtGui.QLabel(m.valid_from_label), 1, 0)
valid_from = QtGui.QLabel(cert.effectiveDate().toString())
now = datetime.utcnow()
if cert.effectiveDate().toPython() > now:
valid_from.setStyleSheet('QLabel { color: red; }')
status.addWidget(valid_from, 1, 1)
status.addWidget(QtGui.QLabel(m.valid_to_label), 1, 2)
valid_to = QtGui.QLabel(cert.expiryDate().toString())
if cert.expiryDate().toPython() < now:
valid_to.setStyleSheet('QLabel { color: red; }')
status.addWidget(valid_to, 1, 3)
layout.addLayout(status)
buttons = QtGui.QHBoxLayout()
export_btn = QtGui.QPushButton(m.export_to_file)
export_btn.clicked.connect(partial(self._export_cert, cert))
buttons.addWidget(export_btn)
delete_btn = QtGui.QPushButton(m.delete_cert)
delete_btn.clicked.connect(
self._controller.wrap(self._delete_cert, True))
buttons.addWidget(delete_btn)
layout.addStretch()
layout.addLayout(buttons)
def _export_cert(self, cert):
fn, fn_filter = QtGui.QFileDialog.getSaveFileName(
self, m.export_cert, filter='Certificate (*.pem *.crt)')
if not fn:
return
with open(fn, 'wb') as f:
f.write(cert.toPem().data())
QtGui.QMessageBox.information(self, m.cert_exported,
m.cert_exported_desc_1 % fn)
def _delete_cert(self, controller, release):
res = QtGui.QMessageBox.warning(self, m.delete_cert,
m.delete_cert_warning_1 % self._slot,
QtGui.QMessageBox.Ok,
QtGui.QMessageBox.Cancel)
if res == QtGui.QMessageBox.Ok:
try:
controller.ensure_authenticated()
worker = QtCore.QCoreApplication.instance().worker
worker.post(
m.deleting_cert,
(controller.delete_certificate, self._slot),
partial(self._delete_cert_callback, controller, release),
True)
except (DeviceGoneError, PivError, ValueError) as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
def _delete_cert_callback(self, controller, release, result):
if isinstance(result, DeviceGoneError):
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.window().accept()
elif isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
self.parent().refresh(controller)
QtGui.QMessageBox.information(self, m.cert_deleted,
m.cert_deleted_desc)
class CertWidget(QtGui.QWidget):
def __init__(self, controller, slot):
super(CertWidget, self).__init__()
self._controller = controller
self._slot = slot
self._build_ui()
controller.use(self.refresh)
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
self._status = QtGui.QLabel(m.cert_not_loaded)
layout.addWidget(self._status)
buttons = QtGui.QHBoxLayout()
from_file_btn = QtGui.QPushButton(m.import_from_file)
from_file_btn.clicked.connect(
self._controller.wrap(self._import_file, True))
if settings[SETTINGS.ENABLE_IMPORT]:
buttons.addWidget(from_file_btn)
generate_btn = QtGui.QPushButton(m.generate_key)
generate_btn.clicked.connect(
self._controller.wrap(self._generate_key, True))
buttons.addWidget(generate_btn)
layout.addLayout(buttons)
def refresh(self, controller):
if controller.pin_blocked:
self.window().accept()
return
self.layout().removeWidget(self._status)
self._status.hide()
if self._slot in controller.certs:
self._status = CertPanel(self._controller, self._slot, self)
else:
self._status = QtGui.QLabel('%s<br><br>%s' % (
USAGES[self._slot], m.cert_not_loaded))
self._status.setWordWrap(True)
self.layout().insertWidget(0, self._status)
def _import_file(self, controller, release):
fn, fn_filter = QtGui.QFileDialog.getOpenFileName(
self, m.import_from_file, filter=FILE_FILTER)
if not fn:
return
func, needs_password, is_key = import_file(controller, self._slot, fn)
if func is None:
QtGui.QMessageBox.warning(self, m.error, m.unsupported_file)
return
if is_key:
dialog = UsagePolicyDialog(controller, self._slot, self)
if dialog.has_content and dialog.exec_():
func = partial(func, pin_policy=dialog.pin_policy,
touch_policy=dialog.touch_policy)
settings[SETTINGS.TOUCH_POLICY] = dialog.touch_policy
if needs_password:
password, status = get_text(
self, m.enter_file_password, m.password_label,
QtGui.QLineEdit.Password)
if not status:
return
func = partial(func, password=password)
try:
if not controller.poll():
controller.reconnect()
controller.ensure_authenticated()
except Exception as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
# User confirmation for overwriting slot data
if self._slot in controller.certs:
res = QtGui.QMessageBox.warning(
self,
m.overwrite_slot_warning,
m.overwrite_slot_warning_desc % self._slot,
QtGui.QMessageBox.Ok,
QtGui.QMessageBox.Cancel)
if res == QtGui.QMessageBox.Cancel:
return
try:
worker = QtCore.QCoreApplication.instance().worker
worker.post(m.importing_file, func, partial(
self._import_file_callback, controller, release), True)
except (DeviceGoneError, PivError, ValueError) as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
def _import_file_callback(self, controller, release, result):
if isinstance(result, DeviceGoneError):
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.window().accept()
elif isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
self.refresh(controller)
QtGui.QMessageBox.information(self, m.cert_installed,
m.cert_installed_desc)
def _generate_key(self, controller, release):
dialog = GenerateKeyDialog(controller, self._slot, self)
if dialog.exec_():
self.refresh(controller)
class CertDialog(Dialog):
def __init__(self, controller, parent=None):
super(CertDialog, self).__init__(parent)
self.setWindowTitle(m.certificates)
self._complex = settings[SETTINGS.COMPLEX_PINS]
self._controller = controller
controller.on_lost(self.accept)
self._build_ui()
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
# This unfortunately causes the window to resize when switching tabs.
# layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self._cert_tabs = QtGui.QTabWidget()
self._cert_tabs.setMinimumSize(540, 160)
shown_slots = settings[SETTINGS.SHOWN_SLOTS]
selected = False
for (slot, label) in sorted(SLOTS.items()):
if slot in shown_slots:
index = self._cert_tabs.addTab(
CertWidget(self._controller, slot), label)
if not selected:
self._cert_tabs.setCurrentIndex(index)
selected = True
elif not settings.is_locked(SETTINGS.SHOWN_SLOTS):
index = self._cert_tabs.addTab(QtGui.QLabel(), label)
self._cert_tabs.setTabEnabled(index, False)
layout.addWidget(self._cert_tabs) | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/cert.py | cert.py |
from PySide import QtGui, QtCore
from pivman import messages as m
from pivman.utils import has_ca, request_cert_from_ca
from pivman.storage import settings, SETTINGS
from pivman.view.usage_policy_dialog import UsagePolicyDialog
from pivman.view.utils import SUBJECT_VALIDATOR
def save_file_as(parent, title, fn_filter):
return QtGui.QFileDialog.getSaveFileName(parent, title, filter=fn_filter)[0]
def needs_subject(forms):
return bool({'csr', 'ssc', 'ca'}.intersection(forms))
class GenerateKeyDialog(UsagePolicyDialog):
def __init__(self, controller, slot, parent=None):
super(GenerateKeyDialog, self).__init__(controller, slot, parent)
def _build_ui(self):
self.setWindowTitle(m.generate_key)
self.setFixedWidth(400)
layout = QtGui.QVBoxLayout(self)
warning = QtGui.QLabel(m.generate_key_warning_1 % self._slot)
warning.setWordWrap(True)
layout.addWidget(warning)
self._build_algorithms(layout)
self._build_usage_policy(layout)
self._build_output(layout)
def _build_algorithms(self, layout):
self._alg_type = QtGui.QButtonGroup(self)
self._alg_rsa_1024 = QtGui.QRadioButton(m.alg_rsa_1024)
self._alg_rsa_1024.setProperty('value', 'RSA1024')
self._alg_rsa_2048 = QtGui.QRadioButton(m.alg_rsa_2048)
self._alg_rsa_2048.setProperty('value', 'RSA2048')
self._alg_ecc_p256 = QtGui.QRadioButton(m.alg_ecc_p256)
self._alg_ecc_p256.setProperty('value', 'ECCP256')
self._alg_ecc_p384 = QtGui.QRadioButton(m.alg_ecc_p384)
self._alg_ecc_p384.setProperty('value', 'ECCP384')
self._alg_type.addButton(self._alg_rsa_1024)
self._alg_type.addButton(self._alg_rsa_2048)
self._alg_type.addButton(self._alg_ecc_p256)
if self._controller.version_tuple >= (4, 0, 0):
self._alg_type.addButton(self._alg_ecc_p384)
algo = settings[SETTINGS.ALGORITHM]
if settings.is_locked(SETTINGS.ALGORITHM):
layout.addWidget(QtGui.QLabel(m.algorithm_1 % algo))
else:
layout.addWidget(self.section(m.algorithm))
for button in self._alg_type.buttons():
layout.addWidget(button)
if button.property('value') == algo:
button.setChecked(True)
button.setFocus()
if not self._alg_type.checkedButton():
button = self._alg_type.buttons()[0]
button.setChecked(True)
def _build_output(self, layout):
layout.addWidget(self.section(m.output))
self._out_type = QtGui.QButtonGroup(self)
self._out_pk = QtGui.QRadioButton(m.out_pk)
self._out_pk.setProperty('value', 'pk')
self._out_ssc = QtGui.QRadioButton(m.out_ssc)
self._out_ssc.setProperty('value', 'ssc')
self._out_csr = QtGui.QRadioButton(m.out_csr)
self._out_csr.setProperty('value', 'csr')
self._out_ca = QtGui.QRadioButton(m.out_ca)
self._out_ca.setProperty('value', 'ca')
self._out_type.addButton(self._out_pk)
self._out_type.addButton(self._out_ssc)
self._out_type.addButton(self._out_csr)
out_btns = []
for button in self._out_type.buttons():
value = button.property('value')
if value in settings[SETTINGS.SHOWN_OUT_FORMS]:
layout.addWidget(button)
out_btns.append(button)
if value == settings[SETTINGS.OUT_TYPE]:
button.setChecked(True)
self._cert_tmpl = QtGui.QLineEdit(settings[SETTINGS.CERTREQ_TEMPLATE])
if 'ca' in settings[SETTINGS.SHOWN_OUT_FORMS]:
if has_ca():
out_btns.append(self._out_ca)
self._out_type.addButton(self._out_ca)
self._out_ca.setChecked(True)
layout.addWidget(self._out_ca)
if not settings.is_locked(SETTINGS.CERTREQ_TEMPLATE):
cert_box = QtGui.QHBoxLayout()
cert_box.addWidget(QtGui.QLabel(m.cert_tmpl))
cert_box.addWidget(self._cert_tmpl)
layout.addLayout(cert_box)
else:
layout.addWidget(QtGui.QLabel(m.ca_not_connected))
self._out_type.buttonClicked.connect(self._output_changed)
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
self._subject = QtGui.QLineEdit(settings[SETTINGS.SUBJECT])
self._subject.setValidator(SUBJECT_VALIDATOR)
today = QtCore.QDate.currentDate()
self._expire_date = QtGui.QDateTimeEdit(today.addYears(1))
self._expire_date.setDisplayFormat("yyyy-MM-dd")
self._expire_date.setMinimumDate(today.addDays(1))
if not out_btns:
layout.addWidget(QtGui.QLabel(m.no_output))
buttons.button(QtGui.QDialogButtonBox.Ok).setDisabled(True)
else:
if not settings.is_locked(SETTINGS.SUBJECT) and \
needs_subject([b.property('value') for b in out_btns]):
subject_box = QtGui.QHBoxLayout()
subject_box.addWidget(QtGui.QLabel(m.subject))
subject_box.addWidget(self._subject)
layout.addLayout(subject_box)
expire_date = QtGui.QHBoxLayout()
expire_date.addWidget(QtGui.QLabel(m.expiration_date))
expire_date.addWidget(self._expire_date)
layout.addLayout(expire_date)
out_btn = self._out_type.checkedButton()
if out_btn is None:
out_btn = out_btns[0]
out_btn.setChecked(True)
self._output_changed(out_btn)
buttons.accepted.connect(self._generate)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def _output_changed(self, btn):
self._cert_tmpl.setEnabled(btn is self._out_ca)
self._subject.setDisabled(btn is self._out_pk)
self._expire_date.setDisabled(btn is not self._out_ssc)
@property
def algorithm(self):
if settings.is_locked(SETTINGS.ALGORITHM):
return settings[SETTINGS.ALGORITHM]
return self._alg_type.checkedButton().property('value')
@property
def out_format(self):
return self._out_type.checkedButton().property('value')
def _generate(self):
if self.out_format != 'pk' and not \
self._subject.hasAcceptableInput():
QtGui.QMessageBox.warning(self, m.invalid_subject,
m.invalid_subject_desc)
self._subject.setFocus()
self._subject.selectAll()
return
if self.out_format == 'pk':
out_fn = save_file_as(self, m.save_pk, 'Public Key (*.pem)')
if not out_fn:
return
elif self.out_format == 'csr':
out_fn = save_file_as(self, m.save_csr,
'Certificate Signing Reqest (*.csr)')
if not out_fn:
return
else:
out_fn = None
try:
if not self._controller.poll():
self._controller.reconnect()
if self.out_format != 'pk':
pin = self._controller.ensure_pin()
else:
pin = None
self._controller.ensure_authenticated(pin)
except Exception as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
return
valid_days = QtCore.QDate.currentDate().daysTo(self._expire_date.date())
# User confirmation for overwriting slot data
if self._slot in self._controller.certs:
res = QtGui.QMessageBox.warning(
self,
m.overwrite_slot_warning,
m.overwrite_slot_warning_desc % self._slot,
QtGui.QMessageBox.Ok,
QtGui.QMessageBox.Cancel)
if res == QtGui.QMessageBox.Cancel:
return
worker = QtCore.QCoreApplication.instance().worker
worker.post(
m.generating_key, (self._do_generate, pin, out_fn, valid_days),
self._generate_callback, True)
def _do_generate(self, pin=None, out_fn=None, valid_days=365):
data = self._controller.generate_key(self._slot, self.algorithm,
self.pin_policy,
self.touch_policy)
return (self._do_generate2, data, pin, out_fn, valid_days)
def _generate_callback(self, result):
if isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
busy_message = m.generating_key
if self.touch_policy and self.out_format in ['ssc', 'csr', 'ca']:
QtGui.QMessageBox.information(self, m.touch_needed,
m.touch_needed_desc)
busy_message = m.touch_prompt
worker = QtCore.QCoreApplication.instance().worker
worker.post(busy_message, result, self._generate_callback2, True)
def _do_generate2(self, data, pin, out_fn, valid_days=365):
subject = self._subject.text()
if self.out_format in ['csr', 'ca']:
data = self._controller.create_csr(self._slot, pin, data, subject)
if self.out_format in ['pk', 'csr']:
with open(out_fn, 'w') as f:
f.write(data)
return out_fn
else:
if self.out_format == 'ssc':
cert = self._controller.selfsign_certificate(
self._slot, pin, data, subject, valid_days)
elif self.out_format == 'ca':
cert = request_cert_from_ca(data, self._cert_tmpl.text())
self._controller.import_certificate(cert, self._slot)
def _generate_callback2(self, result):
if isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
settings[SETTINGS.ALGORITHM] = self.algorithm
if self._controller.version_tuple >= (4, 0, 0):
settings[SETTINGS.TOUCH_POLICY] = self.touch_policy
settings[SETTINGS.OUT_TYPE] = self.out_format
if self.out_format != 'pk' and not \
settings.is_locked(SETTINGS.SUBJECT):
subject = self._subject.text()
# Only save if different:
if subject != settings[SETTINGS.SUBJECT]:
settings[SETTINGS.SUBJECT] = subject
if self.out_format == 'ca':
settings[SETTINGS.CERTREQ_TEMPLATE] = self._cert_tmpl.text()
message = m.generated_key_desc_1 % self._slot
if self.out_format == 'pk':
message += '\n' + m.gen_out_pk_1 % result
elif self.out_format == 'csr':
message += '\n' + m.gen_out_csr_1 % result
elif self.out_format == 'ssc':
message += '\n' + m.gen_out_ssc
elif self.out_format == 'ca':
message += '\n' + m.gen_out_ca
QtGui.QMessageBox.information(self, m.generated_key, message)
self.accept() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/generate_dialog.py | generate_dialog.py |
from PySide import QtGui
from PySide import QtCore
from pivman import messages as m
from pivman.utils import is_macos_sierra_or_later
from pivman.watcher import ControllerWatcher
from pivman.view.utils import IMPORTANT
from pivman.view.init_dialog import InitDialog, MacOSPairingDialog
from pivman.view.set_pin_dialog import SetPinDialog
from pivman.view.manage import ManageDialog
from pivman.view.cert import CertDialog
class MainWidget(QtGui.QWidget):
def __init__(self):
super(MainWidget, self).__init__()
self._lock = QtCore.QMutex()
self._controller = ControllerWatcher()
self._build_ui()
self._controller.on_found(self._refresh_controller)
self._controller.on_lost(self._no_controller)
self._no_controller()
def showEvent(self, event):
self.refresh()
event.accept()
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
btns = QtGui.QHBoxLayout()
self._cert_btn = QtGui.QPushButton(m.certificates)
self._cert_btn.clicked.connect(self._manage_certs)
btns.addWidget(self._cert_btn)
self._pin_btn = QtGui.QPushButton(m.manage_pin)
self._pin_btn.clicked.connect(self._manage_pin)
btns.addWidget(self._pin_btn)
self._setup_macos_btn = QtGui.QPushButton(m.setup_for_macos)
if is_macos_sierra_or_later():
self._setup_macos_btn.clicked.connect(
self._controller.wrap(self._setup_for_macos))
btns.addWidget(self._setup_macos_btn)
layout.addLayout(btns)
self._messages = QtGui.QTextEdit()
self._messages.setFixedSize(480, 100)
self._messages.setReadOnly(True)
layout.addWidget(self._messages)
def _manage_pin(self):
ManageDialog(self._controller, self).exec_()
self.refresh()
def _manage_certs(self):
CertDialog(self._controller, self).exec_()
self.refresh()
def _setup_for_macos(self, controller):
MacOSPairingDialog(controller, self).exec_()
self.refresh()
def refresh(self):
self._controller.use(self._refresh_controller)
def _no_controller(self):
self._pin_btn.setEnabled(False)
self._cert_btn.setEnabled(False)
self._setup_macos_btn.setEnabled(False)
self._messages.setHtml(m.no_key)
def _refresh_controller(self, controller):
if not controller.poll():
self._no_controller()
return
self._pin_btn.setEnabled(True)
self._cert_btn.setDisabled(controller.pin_blocked)
self._setup_macos_btn.setDisabled(controller.pin_blocked)
messages = []
if controller.pin_blocked:
messages.append(IMPORTANT % m.pin_blocked)
messages.append(m.key_with_applet_1
% controller.version.decode('ascii'))
n_certs = len(controller.certs)
messages.append(m.certs_loaded_1 % n_certs or m.no)
self._messages.setHtml('<br>'.join(messages))
if controller.is_uninitialized():
dialog = InitDialog(controller, self)
if dialog.exec_():
if controller.should_show_macos_dialog():
self._setup_for_macos(controller)
else:
self.refresh()
elif controller.is_pin_expired() and not controller.pin_blocked:
dialog = SetPinDialog(controller, self, True)
if dialog.exec_():
self.refresh() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/main.py | main.py |
from PySide import QtCore, QtGui
from pivman import messages as m
from pivman.view.set_pin_dialog import (SetPinDialog, SetPukDialog,
ResetPinDialog)
from pivman.view.set_key_dialog import SetKeyDialog
from pivman.view.utils import IMPORTANT, Dialog
from pivman.storage import settings, SETTINGS
from functools import partial
class ManageDialog(Dialog):
def __init__(self, controller, parent=None):
super(ManageDialog, self).__init__(parent)
self.setWindowTitle(m.manage_pin)
# self.setFixedSize(480, 180)
self._controller = controller
self._build_ui()
self._controller.on_found(self.refresh)
self._controller.on_lost(self.accept)
self._controller.use(self.refresh)
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
btns = QtGui.QHBoxLayout()
self._pin_btn = QtGui.QPushButton(m.change_pin)
self._pin_btn.clicked.connect(self._controller.wrap(self._change_pin,
True))
btns.addWidget(self._pin_btn)
self._puk_btn = QtGui.QPushButton(m.change_puk)
self._puk_btn.clicked.connect(self._controller.wrap(self._change_puk,
True))
self._key_btn = QtGui.QPushButton(m.change_key)
self._key_btn.clicked.connect(self._controller.wrap(self._change_key,
True))
if not settings.is_locked(SETTINGS.PIN_AS_KEY) or \
not settings[SETTINGS.PIN_AS_KEY]:
btns.addWidget(self._puk_btn)
btns.addWidget(self._key_btn)
layout.addLayout(btns)
self._messages = QtGui.QTextEdit()
self._messages.setFixedSize(480, 100)
self._messages.setReadOnly(True)
layout.addWidget(self._messages)
def refresh(self, controller):
messages = []
if controller.pin_blocked:
messages.append(IMPORTANT % m.pin_blocked)
elif controller.does_pin_expire():
days_left = controller.get_pin_days_left()
message = m.pin_days_left_1 % days_left
if days_left < 7:
message = IMPORTANT % message
messages.append(message)
if controller.pin_is_key:
messages.append(m.pin_is_key)
if controller.puk_blocked:
messages.append(m.puk_blocked)
if controller.pin_blocked:
if controller.puk_blocked:
self._pin_btn.setText(m.reset_device)
else:
self._pin_btn.setText(m.reset_pin)
else:
self._pin_btn.setText(m.change_pin)
self._puk_btn.setDisabled(controller.puk_blocked)
self._key_btn.setDisabled(controller.pin_is_key and
controller.pin_blocked)
self._messages.setHtml('<br>'.join(messages))
def _change_pin(self, controller, release):
if controller.pin_blocked:
if controller.puk_blocked:
res = QtGui.QMessageBox.warning(
self, m.reset_device, m.reset_device_warning,
QtGui.QMessageBox.Ok, QtGui.QMessageBox.Cancel)
if res == QtGui.QMessageBox.Ok:
worker = QtCore.QCoreApplication.instance().worker
worker.post(m.resetting_device, controller.reset_device,
partial(self._reset_callback, release), True)
return
else:
dialog = ResetPinDialog(controller, self)
else:
dialog = SetPinDialog(controller, self)
if dialog.exec_():
self.refresh(controller)
def _change_puk(self, controller, release):
dialog = SetPukDialog(controller, self)
if dialog.exec_():
self.refresh(controller)
def _change_key(self, controller, release):
dialog = SetKeyDialog(controller, self)
if dialog.exec_():
QtGui.QMessageBox.information(self, m.key_changed,
m.key_changed_desc)
self.refresh(controller)
def _reset_callback(self, release, result):
QtGui.QMessageBox.information(self, m.device_resetted,
m.device_resetted_desc)
self.accept() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/manage.py | manage.py |
from PySide import QtGui
from pivman import messages as m
from pivman.storage import settings, SETTINGS
from pivman.yubicommon import qt
class UsagePolicyDialog(qt.Dialog):
def __init__(self, controller, slot, parent=None):
super(UsagePolicyDialog, self).__init__(parent)
self._controller = controller
self._slot = slot
self.has_content = False
self._build_ui()
def _build_ui(self):
self.setWindowTitle(m.usage_policy)
self.setFixedWidth(400)
layout = QtGui.QVBoxLayout(self)
self._build_usage_policy(layout)
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def _build_usage_policy(self, layout):
self._pin_policy = QtGui.QComboBox()
self._pin_policy.addItem(m.pin_policy_default, None)
self._pin_policy.addItem(m.pin_policy_never, 'never')
self._pin_policy.addItem(m.pin_policy_once, 'once')
self._pin_policy.addItem(m.pin_policy_always, 'always')
self._touch_policy = QtGui.QCheckBox(m.touch_policy)
if self._controller.version_tuple < (4, 0, 0):
return
use_pin_policy = self._slot in settings[SETTINGS.PIN_POLICY_SLOTS]
use_touch_policy = self._slot in settings[SETTINGS.TOUCH_POLICY_SLOTS]
if use_pin_policy or use_touch_policy:
self.has_content = True
layout.addWidget(self.section(m.usage_policy))
if use_pin_policy:
pin_policy = settings[SETTINGS.PIN_POLICY]
for index in range(self._pin_policy.count()):
if self._pin_policy.itemData(index) == pin_policy:
pin_policy_text = self._pin_policy.itemText(index)
self._pin_policy.setCurrentIndex(index)
break
else:
pin_policy = None
pin_policy_text = m.pin_policy_default
if settings.is_locked(SETTINGS.PIN_POLICY):
layout.addWidget(QtGui.QLabel(m.pin_policy_1 % pin_policy_text))
else:
pin_policy_box = QtGui.QHBoxLayout()
pin_policy_box.addWidget(QtGui.QLabel(m.pin_policy))
pin_policy_box.addWidget(self._pin_policy)
layout.addLayout(pin_policy_box)
if use_touch_policy:
self._touch_policy.setChecked(settings[SETTINGS.TOUCH_POLICY])
self._touch_policy.setDisabled(
settings.is_locked(SETTINGS.TOUCH_POLICY))
layout.addWidget(self._touch_policy)
@property
def pin_policy(self):
if settings.is_locked(SETTINGS.PIN_POLICY):
return settings[SETTINGS.PIN_POLICY]
return self._pin_policy.itemData(self._pin_policy.currentIndex())
@property
def touch_policy(self):
if self._controller.version_tuple < (4, 0, 0):
return False
if settings.is_locked(SETTINGS.TOUCH_POLICY):
return settings[SETTINGS.TOUCH_POLICY]
return self._touch_policy.isChecked() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/usage_policy_dialog.py | usage_policy_dialog.py |
from PySide import QtGui, QtCore
from pivman import messages as m
from pivman.piv import DeviceGoneError, PivError, WrongPinError, KEY_LEN
from pivman.view.set_pin_dialog import SetPinDialog
from pivman.view.utils import KEY_VALIDATOR, pin_field
from pivman.utils import complexity_check
from pivman.storage import settings, SETTINGS
from pivman.yubicommon import qt
from binascii import b2a_hex
from pivman.controller import AUTH_SLOT, ENCRYPTION_SLOT
import os
import re
NUMERIC_PATTERN = re.compile("^[0-9]+$")
class PinPanel(QtGui.QWidget):
def __init__(self, headers):
super(PinPanel, self).__init__()
self._complex = settings[SETTINGS.COMPLEX_PINS]
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
rowLayout = QtGui.QFormLayout()
rowLayout.addRow(headers.section(m.pin))
self._new_pin = pin_field()
rowLayout.addRow(m.new_pin_label, self._new_pin)
self._confirm_pin = pin_field()
rowLayout.addRow(m.verify_pin_label, self._confirm_pin)
layout.addLayout(rowLayout)
self._non_numeric_pin_warning = QtGui.QLabel(m.non_numeric_pin_warning)
self._non_numeric_pin_warning.setWordWrap(True)
layout.addWidget(self._non_numeric_pin_warning)
@property
def pin(self):
error = None
new_pin = self._new_pin.text()
if not new_pin:
error = m.pin_empty
elif new_pin != self._confirm_pin.text():
error = m.pin_confirm_mismatch
elif self._complex and not complexity_check(new_pin):
error = m.pin_complexity_desc
if error:
self._new_pin.setText('')
self._confirm_pin.setText('')
self._new_pin.setFocus()
raise ValueError(error)
return new_pin
class KeyPanel(QtGui.QWidget):
def __init__(self, headers):
super(KeyPanel, self).__init__()
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(headers.section(m.management_key))
self._key_type = QtGui.QButtonGroup(self)
self._kt_pin = QtGui.QRadioButton(m.use_pin_as_key, self)
self._kt_key = QtGui.QRadioButton(m.use_separate_key, self)
self._key_type.addButton(self._kt_pin)
self._key_type.addButton(self._kt_key)
self._key_type.buttonClicked.connect(self._change_key_type)
layout.addWidget(self._kt_pin)
layout.addWidget(self._kt_key)
self._adv_panel = AdvancedPanel(headers)
if settings[SETTINGS.PIN_AS_KEY]:
self._kt_pin.setChecked(True)
else:
self._kt_key.setChecked(True)
self.layout().addWidget(self._adv_panel)
def _change_key_type(self, btn):
if btn == self._kt_pin:
self.layout().removeWidget(self._adv_panel)
self._adv_panel.hide()
else:
self._adv_panel.reset()
self.layout().addWidget(self._adv_panel)
self._adv_panel.show()
self.adjustSize()
self.parentWidget().adjustSize()
@property
def use_pin(self):
return self._key_type.checkedButton() == self._kt_pin
@property
def puk(self):
return self._adv_panel.puk if not self.use_pin else None
@property
def key(self):
return self._adv_panel.key if not self.use_pin else None
class AdvancedPanel(QtGui.QWidget):
def __init__(self, headers):
super(AdvancedPanel, self).__init__()
self._complex = settings[SETTINGS.COMPLEX_PINS]
layout = QtGui.QFormLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addRow(QtGui.QLabel(m.key_label))
self._key = QtGui.QLineEdit()
self._key.setValidator(KEY_VALIDATOR)
self._key.textChanged.connect(self._validate_key)
layout.addRow(self._key)
buttons = QtGui.QDialogButtonBox()
self._randomize_btn = QtGui.QPushButton(m.randomize)
self._randomize_btn.clicked.connect(self.randomize)
self._copy_btn = QtGui.QPushButton(m.copy_clipboard)
self._copy_btn.clicked.connect(self._copy)
buttons.addButton(self._randomize_btn,
QtGui.QDialogButtonBox.ActionRole)
buttons.addButton(self._copy_btn, QtGui.QDialogButtonBox.ActionRole)
layout.addRow(buttons)
layout.addRow(headers.section(m.puk))
self._puk = pin_field()
layout.addRow(m.new_puk_label, self._puk)
self._confirm_puk = pin_field()
layout.addRow(m.verify_puk_label, self._confirm_puk)
def reset(self):
self.randomize()
self._puk.setText('')
self._confirm_puk.setText('')
def randomize(self):
self._key.setText(b2a_hex(os.urandom(KEY_LEN)).decode('ascii'))
def _validate_key(self):
self._copy_btn.setDisabled(not self._key.hasAcceptableInput())
def _copy(self):
self._key.selectAll()
self._key.copy()
self._key.deselect()
@property
def key(self):
if not self._key.hasAcceptableInput():
self._key.setText('')
self._key.setFocus()
raise ValueError(m.key_invalid_desc)
return self._key.text()
@property
def puk(self):
error = None
puk = self._puk.text()
if not puk:
return None
elif self._complex and not complexity_check(puk):
error = m.puk_not_complex
elif puk != self._confirm_puk.text():
error = m.puk_confirm_mismatch
if error:
self._puk.setText('')
self._confirm_puk.setText('')
self._puk.setFocus()
raise ValueError(error)
return puk
class InitDialog(qt.Dialog):
def __init__(self, controller, parent=None):
super(InitDialog, self).__init__(parent)
self.setWindowTitle(m.initialize)
self.setMinimumWidth(400)
self._controller = controller
self._build_ui()
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
self._pin_panel = PinPanel(self.headers)
layout.addWidget(self._pin_panel)
self._key_panel = KeyPanel(self.headers)
if not settings.is_locked(SETTINGS.PIN_AS_KEY) or \
not settings[SETTINGS.PIN_AS_KEY]:
layout.addWidget(self._key_panel)
layout.addStretch()
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok)
self._ok_btn = buttons.button(QtGui.QDialogButtonBox.Ok)
buttons.accepted.connect(self._initialize)
layout.addWidget(buttons)
def _initialize(self):
try:
pin = self._pin_panel.pin
key = self._key_panel.key
puk = self._key_panel.puk
if key is not None and puk is None:
res = QtGui.QMessageBox.warning(self, m.no_puk,
m.no_puk_warning,
QtGui.QMessageBox.Ok,
QtGui.QMessageBox.Cancel)
if res != QtGui.QMessageBox.Ok:
return
if not self._controller.poll():
self._controller.reconnect()
self._controller.ensure_authenticated()
worker = QtCore.QCoreApplication.instance().worker
worker.post(
m.initializing,
(self._controller.initialize, pin, puk, key),
self._init_callback,
True
)
except DeviceGoneError:
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.close()
except (PivError, ValueError) as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
def _init_callback(self, result):
if isinstance(result, DeviceGoneError):
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.close()
if isinstance(result, WrongPinError):
QtGui.QMessageBox.warning(self, m.error, m.not_default_pin)
self.close()
elif isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
if not settings.is_locked(SETTINGS.PIN_AS_KEY):
settings[SETTINGS.PIN_AS_KEY] = self._key_panel.use_pin
self.accept()
class MacOSPairingDialog(qt.Dialog):
def __init__(self, controller, parent=None):
super(MacOSPairingDialog, self).__init__(parent)
self.setWindowTitle(m.macos_pairing_title)
self._controller = controller
self._build_ui()
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
lbl = QtGui.QLabel(m.macos_pairing_desc)
lbl.setWordWrap(True)
layout.addWidget(lbl)
buttons = QtGui.QDialogButtonBox()
yes_btn = buttons.addButton(QtGui.QDialogButtonBox.Yes)
yes_btn.setDefault(True)
no_btn = buttons.addButton(QtGui.QDialogButtonBox.No)
no_btn.setAutoDefault(False)
no_btn.setDefault(False)
buttons.accepted.connect(self._setup)
buttons.rejected.connect(self.close)
layout.addWidget(buttons)
def _setup(self):
try:
if not self._controller.poll():
self._controller.reconnect()
pin = self._controller.ensure_pin()
if NUMERIC_PATTERN.match(pin):
self._controller.ensure_authenticated(pin)
# User confirmation for overwriting slot data
if (AUTH_SLOT in self._controller.certs
or ENCRYPTION_SLOT in self._controller.certs):
res = QtGui.QMessageBox.warning(
self,
m.overwrite_slot_warning,
m.overwrite_slot_warning_macos,
QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Ok)
if res == QtGui.QMessageBox.Cancel:
return
worker = QtCore.QCoreApplication.instance().worker
worker.post(
m.setting_up_macos,
(self._controller.setup_for_macos, pin),
self.setup_callback,
True
)
else:
res = QtGui.QMessageBox.warning(
self,
m.error,
m.non_numeric_pin,
QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if res == QtGui.QMessageBox.Yes:
SetPinDialog(self._controller, self).exec_()
except DeviceGoneError:
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.close()
except Exception as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
def setup_callback(self, result):
if isinstance(result, DeviceGoneError):
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.close()
elif isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
QtGui.QMessageBox.information(
self, m.setup_macos_compl, m.setup_macos_compl_desc)
self.accept() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/init_dialog.py | init_dialog.py |
from PySide import QtGui
from pivman import messages as m
from pivman.yubicommon import qt
from pivman.storage import settings, SETTINGS
class SettingsDialog(qt.Dialog):
def __init__(self, parent=None):
super(SettingsDialog, self).__init__(parent)
self.setWindowTitle(m.settings)
self._build_ui()
def _build_ui(self):
layout = QtGui.QFormLayout(self)
layout.addRow(self.section(m.pin))
self._complex_pins = QtGui.QCheckBox(m.use_complex_pins)
self._complex_pins.setChecked(settings[SETTINGS.COMPLEX_PINS])
self._complex_pins.setDisabled(
settings.is_locked(SETTINGS.COMPLEX_PINS))
layout.addRow(self._complex_pins)
self._pin_expires = QtGui.QCheckBox(m.pin_expires)
self._pin_expires_days = QtGui.QSpinBox()
self._pin_expires_days.setMinimum(30)
pin_expires = settings[SETTINGS.PIN_EXPIRATION]
pin_expiry_locked = settings.is_locked(SETTINGS.PIN_EXPIRATION)
self._pin_expires.setChecked(bool(pin_expires))
self._pin_expires_days.setValue(pin_expires)
self._pin_expires.setDisabled(pin_expiry_locked)
self._pin_expires_days.setDisabled(
pin_expiry_locked or not pin_expires)
self._pin_expires.stateChanged.connect(
self._pin_expires_days.setEnabled)
layout.addRow(self._pin_expires)
layout.addRow(m.pin_expires_days, self._pin_expires_days)
layout.addRow(self.section(m.misc))
reader_pattern = settings[SETTINGS.CARD_READER]
self._reader_pattern = QtGui.QLineEdit(reader_pattern)
layout.addRow(m.reader_name, self._reader_pattern)
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
buttons.accepted.connect(self._save)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def _pin_expires_changed(self, val):
self._pin_expires_days.setEnabled(val)
def _save(self):
settings[SETTINGS.COMPLEX_PINS] = self._complex_pins.isChecked()
settings[SETTINGS.CARD_READER] = self._reader_pattern.text()
if self._pin_expires.isChecked():
settings[SETTINGS.PIN_EXPIRATION] = self._pin_expires_days.value()
else:
settings[SETTINGS.PIN_EXPIRATION] = 0
self.accept() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/settings_dialog.py | settings_dialog.py |
from PySide import QtGui, QtCore
from pivman import messages as m
from pivman.piv import DeviceGoneError, PivError, KEY_LEN
from pivman.view.utils import KEY_VALIDATOR
from pivman.yubicommon import qt
from binascii import b2a_hex
import os
class SetKeyDialog(qt.Dialog):
def __init__(self, controller, parent=None):
super(SetKeyDialog, self).__init__(parent)
self._controller = controller
self._build_ui()
kt = self._kt_pin if self._controller.pin_is_key else self._kt_key
kt.setChecked(True)
self._change_key_type(kt)
def _build_ui(self):
self.setWindowTitle(m.change_key)
self.setMinimumWidth(400)
layout = QtGui.QVBoxLayout(self)
self._current_key = QtGui.QLineEdit()
self._current_key.setValidator(KEY_VALIDATOR)
self._current_key.textChanged.connect(self._validate)
if not self._controller.pin_is_key:
layout.addWidget(QtGui.QLabel(m.current_key_label))
layout.addWidget(self._current_key)
self._key_type = QtGui.QButtonGroup(self)
self._kt_pin = QtGui.QRadioButton(m.use_pin_as_key, self)
self._kt_key = QtGui.QRadioButton(m.use_separate_key, self)
self._key_type.addButton(self._kt_pin)
self._key_type.addButton(self._kt_key)
self._key_type.buttonClicked.connect(self._change_key_type)
layout.addWidget(self._kt_pin)
layout.addWidget(self._kt_key)
layout.addWidget(QtGui.QLabel(m.new_key_label))
self._key = QtGui.QLineEdit()
self._key.setValidator(KEY_VALIDATOR)
self._key.textChanged.connect(self._validate)
layout.addWidget(self._key)
buttons = QtGui.QDialogButtonBox()
self._randomize_btn = QtGui.QPushButton(m.randomize)
self._randomize_btn.clicked.connect(self.randomize)
self._copy_btn = QtGui.QPushButton(m.copy_clipboard)
self._copy_btn.clicked.connect(self._copy)
buttons.addButton(self._randomize_btn,
QtGui.QDialogButtonBox.ActionRole)
buttons.addButton(self._copy_btn, QtGui.QDialogButtonBox.ActionRole)
layout.addWidget(buttons)
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
self._ok_btn = buttons.button(QtGui.QDialogButtonBox.Ok)
self._ok_btn.setDisabled(True)
buttons.accepted.connect(self._set_key)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
@property
def use_pin(self):
return self._key_type.checkedButton() == self._kt_pin
def _change_key_type(self, btn):
if btn == self._kt_pin:
self._key.setText('')
self._key.setEnabled(False)
self._randomize_btn.setEnabled(False)
self._copy_btn.setEnabled(False)
else:
self.randomize()
self._key.setEnabled(True)
self._randomize_btn.setEnabled(True)
self._copy_btn.setEnabled(True)
self._validate()
def randomize(self):
self._key.setText(b2a_hex(os.urandom(KEY_LEN)).decode('ascii'))
def _copy(self):
self._key.selectAll()
self._key.copy()
self._key.deselect()
def _validate(self):
old_ok = self._controller.pin_is_key \
or self._current_key.hasAcceptableInput()
new_ok = self.use_pin or self._key.hasAcceptableInput()
self._copy_btn.setEnabled(not self.use_pin and new_ok)
self._ok_btn.setEnabled(old_ok and new_ok)
def _set_key(self):
if self.use_pin and self._controller.pin_is_key:
self.reject()
return
if not self._controller.puk_blocked and self.use_pin:
res = QtGui.QMessageBox.warning(self, m.block_puk,
m.block_puk_desc,
QtGui.QMessageBox.Ok,
QtGui.QMessageBox.Cancel)
if res != QtGui.QMessageBox.Ok:
return
try:
if not self._controller.poll():
self._controller.reconnect()
if self._controller.pin_is_key or self.use_pin:
pin = self._controller.ensure_pin()
else:
pin = None
current_key = pin \
if self._controller.pin_is_key else self._current_key.text()
new_key = pin if self.use_pin else self._key.text()
self._controller.ensure_authenticated(current_key)
worker = QtCore.QCoreApplication.instance().worker
worker.post(m.changing_key, (self._controller.set_authentication,
new_key, self.use_pin),
self._set_key_callback, True)
except (DeviceGoneError, PivError, ValueError) as e:
QtGui.QMessageBox.warning(self, m.error, str(e))
self.reject()
def _set_key_callback(self, result):
if isinstance(result, DeviceGoneError):
QtGui.QMessageBox.warning(self, m.error, m.device_unplugged)
self.accept()
elif isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
else:
self.accept() | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/set_key_dialog.py | set_key_dialog.py |
from PySide import QtGui, QtCore
from pivman import messages as m
from pivman.piv import WrongPinError
from pivman.storage import settings, SETTINGS
from pivman.utils import complexity_check
from pivman.view.utils import pin_field
from pivman.yubicommon import qt
class SetPinDialog(qt.Dialog):
window_title = m.change_pin
label_current = m.current_pin_label
label_new = m.new_pin_label
label_verify = m.verify_pin_label
warn_not_changed = m.pin_not_changed
desc_not_changed = m.pin_not_changed_desc
warn_not_complex = m.pin_not_complex
busy = m.changing_pin
info_changed = m.pin_changed
desc_changed = m.pin_changed_desc
def __init__(self, controller, parent=None, forced=False):
super(SetPinDialog, self).__init__(parent)
self._complex = settings[SETTINGS.COMPLEX_PINS]
self._controller = controller
self._build_ui(forced)
def _build_ui(self, forced):
self.setWindowTitle(self.window_title)
layout = QtGui.QVBoxLayout(self)
if forced:
layout.addWidget(QtGui.QLabel(m.change_pin_forced_desc))
layout.addWidget(QtGui.QLabel(self.label_current))
self._old_pin = pin_field()
layout.addWidget(self._old_pin)
layout.addWidget(QtGui.QLabel(self.label_new))
self._new_pin = pin_field()
layout.addWidget(self._new_pin)
layout.addWidget(QtGui.QLabel(self.label_verify))
self._confirm_pin = pin_field()
layout.addWidget(self._confirm_pin)
self._new_pin.textChanged.connect(self._check_confirm)
self._confirm_pin.textChanged.connect(self._check_confirm)
if forced:
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok)
else:
buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
self._ok_btn = buttons.button(QtGui.QDialogButtonBox.Ok)
self._ok_btn.setDisabled(True)
buttons.accepted.connect(self._set_pin)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def _check_confirm(self):
new_pin = self._new_pin.text()
if len(new_pin) > 0 and new_pin == self._confirm_pin.text():
self._ok_btn.setDisabled(False)
else:
self._ok_btn.setDisabled(True)
def _invalid_pin(self, title, reason):
QtGui.QMessageBox.warning(self, title, reason)
self._new_pin.setText('')
self._confirm_pin.setText('')
self._new_pin.setFocus()
def _prepare_fn(self, old_pin, new_pin):
self._controller.verify_pin(old_pin)
if self._controller.does_pin_expire():
self._controller.ensure_authenticated(old_pin)
return (self._controller.change_pin, old_pin, new_pin)
def _set_pin(self):
old_pin = self._old_pin.text()
new_pin = self._new_pin.text()
if old_pin == new_pin:
self._invalid_pin(self.warn_not_changed, self.desc_not_changed)
elif self._complex and not complexity_check(new_pin):
self._invalid_pin(self.warn_not_complex, m.pin_complexity_desc)
else:
try:
if not self._controller.poll():
self._controller.reconnect()
fn = self._prepare_fn(old_pin, new_pin)
worker = QtCore.QCoreApplication.instance().worker
worker.post(self.busy, fn, self._change_pin_callback, True)
except Exception as e:
self._change_pin_callback(e)
def _change_pin_callback(self, result):
if isinstance(result, Exception):
QtGui.QMessageBox.warning(self, m.error, str(result))
if isinstance(result, WrongPinError):
self._old_pin.setText('')
self._old_pin.setFocus()
if result.blocked:
self.accept()
else:
self.reject()
else:
QtGui.QMessageBox.information(self, self.info_changed,
self.desc_changed)
self.accept()
class SetPukDialog(SetPinDialog):
window_title = m.change_puk
label_current = m.current_puk_label
label_new = m.new_puk_label
label_verify = m.verify_puk_label
warn_not_changed = m.puk_not_changed
desc_not_changed = m.puk_not_changed_desc
warn_not_complex = m.puk_not_complex
busy = m.changing_puk
info_changed = m.puk_changed
desc_changed = m.puk_changed_desc
def _prepare_fn(self, old_puk, new_puk):
return (self._controller.change_puk, old_puk, new_puk)
class ResetPinDialog(SetPinDialog):
window_title = m.reset_pin
label_current = m.puk_label
label_new = m.new_pin_label
label_verify = m.verify_pin_label
warn_not_changed = m.pin_puk_same
desc_not_changed = m.pin_puk_same_desc
warn_not_complex = m.pin_not_complex
busy = m.changing_pin
info_changed = m.pin_changed
desc_changed = m.pin_changed_desc
def _prepare_fn(self, puk, new_pin):
return (self._controller.reset_pin, puk, new_pin) | yubikey-piv-manager | /yubikey-piv-manager-1.4.2.tar.gz/yubikey-piv-manager-1.4.2/pivman/view/set_pin_dialog.py | set_pin_dialog.py |
yubikey-totp-gui
================
GUI for TOTP with the YubiKey.
Suitable for Two-Factor authentication with Gmail, Dropbox, Github, AWS etc.
Installation
============
Installation with `pip` should be fairly straightforward, but `pyusb` may not
install cleanly as pip will refuse beta software by default.
You will likely need to install the beta version first:
For the stable version:
``pip install pyusb==1.0.0b1 yubikey-totp-gui``
For the development version:
``pip install pyusb==1.0.0b1 git+https://github.com/ldrumm/yubikey-totp-gui.git``
Linux
=====
First, you will need Tkinter installed.
Debian and derivates:
``sudo apt-get install python-tk``
Chances are high that Tkinter will already be installed on everything but a
freshly installed OS.
Permissions Issues
------------------
Some Linux distributions forbid direct access to USB devices, and require
modification of system permissions. The simplest way to do this is to install
your distribution's packaged version of `yubikey-personalization` which takes
care of things for you, or alternatively copy the yubico udev rules:
``sudo curl -o /etc/udev/rules.d/69-yubikey.rules https://raw.githubusercontent.com/Yubico/yubikey-personalization/master/69-yubikey.rules``
``sudo curl -o /etc/udev/rules.d/70-yubikey.rules https://raw.githubusercontent.com/Yubico/yubikey-personalization/master/70-yubikey.rules``
``sudo service udev restart``
Windows
=======
Installation on windows currently has some issues, as python-yubico does not
seem to import properly (on my Windows 7 development machine at least).
However, as Yubico `already offer a windows tool<https://www.yubico.com/applications/internet-services/gmail/>`_
that does essentially the same thing as this project, that software can be used
as an alternative.
Other OSs
=========
I haven't had the opportunity to try this, but if your system has a libusb backend
and is somewhat unixy, it is likely to work just fine.
| yubikey-totp-gui | /yubikey-totp-gui-0.3.1.tar.gz/yubikey-totp-gui-0.3.1/README.rst | README.rst |
import sys
import time
import struct
import yubico
import webbrowser
from Tkinter import (
Tk,
Toplevel,
IntVar,
StringVar,
Entry,
Label,
Menu,
Button,
Radiobutton,
Frame,
Checkbutton,
)
from gettext import gettext as _ #TODO
import tkMessageBox
__all__ = ['MainWindow']
DEFAULT_SLOT = 2
DEFAULT_TIME = 0
DEFAULT_STEP = 30
DEFAULT_DIGITS = 6
def _rzfill(string, to_len):
"""right-pad a string with zeros to the given length"""
if len(string) > to_len:
raise ValueError("string is already longer than to_len")
return string + '0' * (to_len - len(string))
def _base32_to_hex(base32):
"""simple base conversion using the RFC4648 base32 alphabet"""
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
x = 0
for digit in str(base32.upper().strip(' ')):
x = x * len(ALPHABET) + ALPHABET.index(digit)
return hex(x).lstrip('0x').rstrip('L').upper()
class _Credits(object):
"""This class spawns the dialogue to show the license information"""
def __init__(self, parent):
self.parent = parent
top = self.top = Toplevel(parent.root)
Label(top, text=__doc__).grid(columnspan=4)
class _ProgrammingWindow(object):
"""
This class spawns the dialogue to configure programming the
YubiKey with a base32 key for challenge-response SHA1 in either slot.
"""
def __init__(self, parent):
self.parent = parent
top = self.top = Toplevel(parent.root)
Label(top, text="Secret Key(base32):").grid(columnspan=3)
base32_key = Entry(top)
base32_key.grid(row=1, column=0, columnspan=3)
challenge_response_slot = IntVar()
challenge_response_slot_widgets = (
Radiobutton(
top,
text='slot 1',
variable=challenge_response_slot,
value=1,
).grid(row=3, column=0),
Radiobutton(
top,
text='slot 2',
variable=challenge_response_slot,
value=2,
).grid(row=3, column=1),
)
require_button = IntVar()
require_button_widget = Checkbutton(top,
text='Button press required',
variable=require_button,
).grid(row=2, columnspan=3)
require_button.set(1)
submit = Button(top,
text="Program",
command=lambda: self._program_confirm(
challenge_response_slot.get(),
base32_key.get(),
require_button.get()
)
).grid(row=4, column=1)
cancel = Button(
top,
text="Cancel",
command=self._program_cancel
).grid(row=4, column=0)
def _program_cancel(self):
"""guess pylint"""
self.top.destroy()
def _program_confirm(self, slot, base32_key, require_button):
"""Confirms that programming should take place"""
if int(slot) not in (1, 2):
return tkMessageBox.showerror("Error", "Please Choose a slot")
try:
_base32_to_hex(base32_key.replace(' ', ''))
except ValueError:
return tkMessageBox.showerror(
"Error",
"{0} is not a valid base32 key".format(base32_key)
)
try:
serial = self.parent.yk.serial()
except (AttributeError, yubico.yubikey_usb_hid.usb.USBError):
return tkMessageBox.showerror("Error", "No YubiKey detected")
if tkMessageBox.askokcancel(
"Confirm",
"Overwrite slot {0} of key with serial {1}?\n"
"This will purge the existing setup and cannot be undone".format(
slot,
serial
)
):
self._program_key(slot, base32_key, require_button)
else:
self._program_cancel()
def _program_key(self, slot, base32_key, require_button):
"""Once we get here, things get destructive"""
try:
config = self.parent.yk.init_config()
except (AttributeError, yubico.yubikey_usb_hid.usb.USBError):
return tkMessageBox.showerror(
"Error",
"No YubiKey detected"
)
config.extended_flag('SERIAL_API_VISIBLE', True)
config.mode_challenge_response(
'h:' + _rzfill(_base32_to_hex(base32_key), 40),
type='HMAC',
variable=True,
require_button=bool(require_button),
)
try:
self.parent.yk.write_config(config, slot=slot)
tkMessageBox.showinfo(
"Success",
"Successfully programmed YubiKey in slot %s." % slot
)
except (
yubico.yubico_exception.YubicoError,
yubico.yubico_exception.InputError,
yubico.yubikey_usb_hid.usb.USBError
) as e:
tkMessageBox.showerror("Error", e)
self._program_cancel()
class MainWindow(object):
"""
Yubikey TOTP Challenge response root window
Contains options for fetching a TOTP.
"""
def __init__(self, root):
self.key_dialogue = {}
self.root = root
self.frame = Frame(root)
self.frame.grid()
self._menu_setup()
self.version = StringVar()
self.version_widget = Label(
self.frame,
textvariable=self.version
).grid(column=0, row=2)
self.serial = StringVar()
self.serial_widget = Label(
self.frame,
textvariable=self.serial
).grid(column=1, row=2,)
self.yk = None
self.detect_yubikey()
self.slot = IntVar()
self.slot.set(DEFAULT_SLOT)
self.base32_key = StringVar()
self.digits = IntVar()
self.digits.set(DEFAULT_DIGITS)
self.totp = Button(
self.frame,
text="Get TOTP",
command=self.get_totp
).grid(column=0, row=0)
self.challenge_response_slot = (
Radiobutton(text='slot 1',
variable=self.slot,
value=1,
).grid(row=2, column=0),
Radiobutton(text='slot 2',
variable=self.slot,
value=2,
).grid(row=2, column=1)
)
self.digits_radio = (
Radiobutton(text='6 digits',
variable=self.digits,
value=6,
).grid(row=3, column=0),
Radiobutton(text='8 digits',
variable=self.digits,
value=8,
).grid(row=3, column=1)
)
self.user_message = StringVar()
self.user_message.set(
"Choose challenge-response\n"\
"slot, then click 'Get OTP'"
)
self.message_widget = Label(
self.frame,
textvariable=self.user_message
).grid(column=1, row=0, columnspan=2)
self.root.bind_class(self.root, '<KeyPress>', self.keypress)
def _menu_setup(self):
"""Pull-down menus init"""
menu = Menu(self.root)
self.root.config(menu=menu)
file_menu = Menu(menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Quit", command=self.frame.quit)
edit_menu = Menu(menu)
menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Program YubiKey for TOTP...", command=self._program_key)
help_menu = Menu(menu)
menu.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="HowTo...", command=self._help_dialogue)
help_menu.add_command(label="About...", command=self._about_dialogue)
help_menu.add_command(label="Credits...", command=self._credits_dialogue)
def _help_dialogue(self):
"""callback for the help->help pulldown"""
webbrowser.open('https://github.com/ldrumm/yubikey-totp-gui/wiki')
def _about_dialogue(self):
"""callback for the help->about pulldown"""
webbrowser.open('https://github.com/ldrumm/yubikey-totp-gui')
def _credits_dialogue(self):
"""callback for the help->about pulldown"""
credits_dialogue = _Credits(self)
self.root.wait_window(credits_dialogue.top)
def _program_key(self):
"""
callback for the edit->Program YubiKey pulldown
Opens a new configuration window, blocking until exit.
"""
prg_dialogue = _ProgrammingWindow(self)
self.root.wait_window(prg_dialogue.top)
def keypress(self, event):
"""
Event handler for keypress events.
"""
events = {
'1': lambda: self.slot.set(1),
'2': lambda: self.slot.set(2),
'6': lambda: self.digits.set(6),
'8': lambda: self.digits.set(8),
}
try:
events[event.keysym]()
except KeyError:
pass
if event.keysym in ('1', '2', 'Return', 'Enter'):
self.get_totp()
self.root.wm_withdraw()
def detect_yubikey(self):
"""Tries to detect a plugged-in YubiKey else alerts user"""
try:
self.yk = yubico.find_yubikey()
self.version.set("Version:%s" % self.yk.version())
self.serial.set("Serial:%s" % self.yk.serial())
except yubico.yubikey.YubiKeyError:
self.version.set("No YubiKey detected")
self.serial.set("")
self.yk = None
except yubico.yubikey_usb_hid.usb.USBError as e:
self.version.set("No YubiKey detected")
self.serial.set("")
self.user_message.set(
"A USB error occurred:%s - do you have permission to access USB devices?",
e.message
)
def _make_totp(self):
"""
Create an OATH TOTP OTP and return it as a string (to disambiguate leading zeros).
This is ripped straight out of yubico's command-line script, `yubikey-totp`.
Credit due.
"""
secret = struct.pack('> Q', int(time.mktime(time.gmtime())) / DEFAULT_STEP).ljust(64, chr(0x0))
response = self.yk.challenge_response(secret, slot=self.slot.get())
# format with appropriate number of leading zeros
fmt = '%.' + str(self.digits.get()) + 'i'
totp_str = fmt % (yubico.yubico_util.hotp_truncate(response, length=self.digits.get()))
return totp_str
def get_totp(self):
otp = None
self.detect_yubikey()
if self.yk is None:
return
self.user_message.set("Touch the yubikey button")
self.root.update()
try:
otp = self._make_totp()
except (yubico.yubico_exception.YubicoError, yubico.yubikey_usb_hid.usb.USBError) as e:
self.user_message.set(e)
return
if not otp:
self.user_message.set("No TOTP received from YubiKey")
self.root.clipboard_clear()
self.root.clipboard_append(otp)
self.user_message.set("%s\ncopied to clipboard" % otp)
def main():
root = Tk()
root.wm_title('Yubikey-TOTP')
MainWindow(root)
return root.mainloop()
if __name__ == '__main__':
sys.exit(main()) | yubikey-totp-gui | /yubikey-totp-gui-0.3.1.tar.gz/yubikey-totp-gui-0.3.1/src/yubikey_totp_gui.py | yubikey_totp_gui.py |
import sys, os
import urllib2
import hmac
import base64
import hashlib
# XXX: Should be easily configurable
default_api_id = None
default_api_key = ''
class YubikeyError(Exception):
pass
class YubikeyBadKeyError(YubikeyError):
pass
class YubikeyConfigError(YubikeyError):
pass
class YubikeyOtherError(YubikeyError):
pass
class YubikeyReturnCodes(object):
"""The return codes of the web service as defined in
http://www.yubico.com/developers/api/"""
codes = {
'OK': 'The OTP is valid.',
'BAD_OTP': 'The OTP is invalid format.',
'REPLAYED_OTP': 'The OTP has already been seen by the service.',
'BAD_SIGNATURE': 'The HMAC signature verification failed.',
'MISSING_PARAMETER': 'The request lacks parameter given by key info.',
'NO_SUCH_CLIENT': '',
'OPERATION_NOT_ALLOWED': '',
'BACKEND_ERROR': '',
}
ok = ('OK',)
bad = ('BAD_OTP', 'REPLAYED_OTP', 'BAD_SIGNATURE')
config = ('MISSING_PARAMETER', 'NO_SUCH_CLIENT')
other = ('OPERATION_NOT_ALLOWED', 'BACKEND_ERROR')
class YubikeyResponse(object):
"""Parses a response from the web service"""
valid_sections = ('h', 't', 'status', 'info')
return_codes = YubikeyReturnCodes()
def __init__(self, response_lines, api_key=''):
self.api_key = api_key or default_api_key
for line in response_lines:
line = line.strip()
if not line: continue
section, response = line.split('=', 1)
if section in self.valid_sections:
self.__dict__[section] = response
def _make_block(self):
return '&'.join(['%s=%s' % (section, self.__dict__[section])
for section in ('info', 'status', 't')
if self.__dict__.get(section, False)])
def is_valid(self):
"""Returns True if the key is valid, False otherwise"""
if not self.status in self.return_codes.codes:
raise YubikeyOtherError, 'Non-existing status code!'
if self.status in self.return_codes.ok:
return True
if self.status in self.return_codes.other:
raise YubikeyOtherError, self.return_codes.codes.get(self.status, 'Impossible OtherError')
if self.status in self.return_codes.config:
error_msg = self.return_codes.codes.get(self.status, 'Impossible ConfigError')
if self.status == 'MISSING_PARAMETER':
error_msg = '%s: "%s"' % (error_msg, self.info)
raise YubikeyConfigError, error_msg
return False
def is_paranoid_valid(self, api_key=default_api_key):
"""Returns True if the key is valid, False if not, raises an
exception if the response-signature is bad."""
#assert False, 'Not finished'
api_key = api_key or self.api_key
if not api_key:
raise YubikeyConfigError, 'No API Key given, cannot check response for validity'
is_ok = self.is_valid()
block = self._make_block()
hash = hmac.new(base64.b64decode(api_key), block, hashlib.sha1)
if hash.digest() == base64.b64decode(self.h):
return is_ok
raise YubikeyBadKeyError, self.return_codes.codes.get('BAD_SIGNATURE', 'Bad signature')
def dump(otp, api_id=default_api_id, authserver_prefix='http://api.yubico.com/wsapi/verify?id='):
"""Dump the response from the web service"""
url = '%s%s&otp=%s' % (authserver_prefix, api_id, otp)
assert api_id
print urllib2.urlopen(url).read()
def verify(otp, api_id=default_api_id, authserver_prefix='http://api.yubico.com/wsapi/verify?id='):
"""Ask the server using the Yubico Web Services API at
authserver_prefix if the otp is valid."""
assert api_id
url = '%s%s&otp=%s' % (authserver_prefix, api_id, otp)
LINK = urllib2.urlopen(url)
yubiresp = YubikeyResponse(LINK)
return yubiresp.is_valid()
def verify_paranoid(otp, api_id=default_api_id, authserver_prefix='http://api.yubico.com/wsapi/verify?id=',
api_key=default_api_key):
"""Ask the server using the Yubico Web Services API at
authserver_prefix if the otp is valid. Raises an exception if the
response-signature is bad."""
assert api_id
url = '%s%s&otp=%s' % (authserver_prefix, api_id, otp)
LINK = urllib2.urlopen(url)
yubiresp = YubikeyResponse(LINK)
return yubiresp.is_paranoid_valid(api_key=api_key)
if __name__ == '__main__':
usage = """
Usage: %s api_id [api_key] otp
api_id: numeric id of API Key
api_key: API Key belonging to api_id, base64 (optional)
otp: one time password from Yubikey
""" % (os.path.basename(sys.argv[0]))
if len(sys.argv) == 3:
sys.exit(not(verify(sys.argv[-1], sys.argv[1])))
elif len(sys.argv) == 4:
sys.exit(not(verify_paranoid(sys.argv[-1], sys.argv[1], api_key=sys.argv[2])))
else:
print >>sys.stderr, usage | yubikey | /yubikey-0.2.tar.gz/yubikey-0.2/yubikey.py | yubikey.py |
== Yubico Authenticator
image:https://travis-ci.org/Yubico/yubioath-desktop.svg?branch=master["Build Status", link="https://travis-ci.org/Yubico/yubioath-desktop"]
The Yubico Authenticator is a graphical desktop tool and command line tool for
generating Open AuTHentication (OATH) event-based HOTP and time-based TOTP
one-time password codes, with the help of a YubiKey that protects the shared
secrets.
=== Graphical interface
image::usage.gif[]
=== Command line interface
$ yubioath --help
Usage: yubioath [OPTIONS] COMMAND [ARGS]...
Commands:
delete Deletes a credential from the YubiKey.
gui Launches the Yubico Authenticator graphical interface.
password Manage the password used to protect access to the YubiKey.
put Stores a new OATH credential in the YubiKey.
reset Deletes all stored OATH credentials from the YubiKey.
show Print one or more codes from a YubiKey.
=== Installation
The recommended way to install this software including dependencies is by using
the provided precompiled binaries for your platform. For Windows and OS X (10.7
and above), there are installers available for download
https://developers.yubico.com/yubioath-desktop/Releases/[here]. For Ubuntu we
have a custom PPA with a package for it
https://launchpad.net/~yubico/+archive/ubuntu/stable[here].
==== Using pip
You can also install this project using pip, however the dependencies may
require additional tools to build. When installing from pip, you can choose
whether or not you wish to install the graphical application, just the command
line tool, or just the python library. You do so as follows:
$ pip install yubioath-desktop[cli,gui] # This will install everything.
$ pip install yubioath-desktop # This installs only the library.
If you run into problems during installation it will likely be with one of the
dependencies, such as PySide or pyscard. Please see the relevant documentation
for installing each project, provided by those projects.
You will also need libykpers, which is a C library used to manage credentials
using the slot-based approach. Installation instructions for this project is
availabe https://developers.yubico.com/yubikey-personalization/[here].
=== Supported devices
Usage of this software requires a compatible YubiKey device. Yubico
Authenticator is capable of provisioning and using both slot-based credentials
(compatible with any YubiKey that supports OTP) as well as the more powerful
standalone OATH functionality of the YubiKey NEO. To use the standalone OATH
functionality your YubiKey must have the CCID mode enabled, which can be done
by using the https://developers.yubico.com/yubikey-neo-manager/[YubiKey NEO
Manager].
==== Detecting the device when using CCID
Under Linux and OS X this application uses libccid to communicate with the
YubiKey. This library requires that each card reader used is listed in its
configuration file, else the device will not be detected ("Insert a YubiKey..."
will be displayed even though a YubiKey is present). To ensure that your
libccid configuration contains all necessary entries you can run one of the two
files locates in the resources directory of this repository, linux-patch-ccid
or osx-patch-ccid, depending on your OS. You will need to run these scripts as
root. If installing the OS X version from the binary installer, this script
will be run automatically for you.
NOTE: You may have to reboot your computer for the change to the libccid
configuration to take effect!
=== Dependencies
Yubico Authenticator requires click, PySide, yubikey-personalization, pyscard,
and PyCrypto.
=== Working with the source code repository
To work with the source code repository, if you wish to build your own release
or contribute pull requests, follow these steps to set up your environment. If
you just wish to install the application use the pre-build binaries or the
source release packages. This project is developed on a Debian based system,
other OSes may not be supported for development.
==== Installing the dependencies
Make sure to install the needed dependencies:
sudo apt-get install python-setuptools python-crypto python-pyscard \
python-pyside pyside-tools python-click libykpers-1-1 pcscd
==== Check out the code
Run these commands to check out the source code:
git clone --recursive https://github.com/Yubico/yubioath-desktop.git
==== Install the project using pip
Install the project from the source code repository, in development mode:
cd yubioath-desktop # cd into the git repository
python setup.py qt_resources # Generate image resources (requires pyside-tools).
pip install -e .[cli,gui] # Install the code in developer mode, using pip.
You can now run the yubioath and yubioath-gui binaries, and anychanges you make
to the code should be reflected in these commands. To remove the installation, run:
pip uninstall yubioath-desktop
==== Build a source release
To build a source release tar ball, run this command:
python setup.py sdist
The resulting build will be created in the dist/ subdirectory.
=== License
Yubico Authenticator is licensed under GPLv3+, see COPYING for details.
Entypo pictograms by Daniel Bruce - www.entypo.com | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/README | README |
from PySide import QtGui, QtCore
from yubioath import __version__ as version
from yubioath.gui.view.ccid_disabled import CcidDisabledDialog
from yubioath.yubicommon import qt
from ..cli.keystore import CONFIG_HOME
try:
from ..core.legacy_otp import ykpers_version
except ImportError:
ykpers_version = 'None'
from ..core.utils import kill_scdaemon
from ..core.exc import NoSpaceError
from . import messages as m
from .controller import GuiController
from .ccid import CardStatus
from .view.systray import Systray
from .view.codes import CodesWidget
from .view.settings import SettingsDialog
from .view.add_cred import AddCredDialog
from .view.add_cred_legacy import AddCredDialog as AddCredLegacyDialog
from .view.set_password import SetPasswordDialog
import sys
import os
import signal
import argparse
ABOUT_TEXT = """
<h2>%s</h2>
%s<br>
%s
<h4>%s</h4>
%%s
<br><br>
""" % (m.app_name, m.copyright, m.version_1, m.libraries)
class MainWidget(QtGui.QStackedWidget):
def __init__(self, controller):
super(MainWidget, self).__init__()
self._controller = controller
self._build_ui()
controller.refreshed.connect(self._refresh)
controller.ccid_disabled.connect(self.ccid_disabled)
controller.watcher.status_changed.connect(self._set_status)
def ccid_disabled(self):
if not self._controller.mute_ccid_disabled_warning:
dialog = CcidDisabledDialog()
dialog.exec_()
if dialog.do_not_ask_again.isChecked():
self._controller.mute_ccid_disabled_warning = 1
def showEvent(self, event):
event.accept()
def _build_ui(self):
self.codes_widget = CodesWidget(self._controller)
self.no_key_widget = QtGui.QLabel(m.no_key)
self.no_key_widget.setAlignment(QtCore.Qt.AlignCenter)
self.addWidget(self.no_key_widget)
self.addWidget(self.codes_widget)
def _refresh(self):
if self._controller.credentials is None:
self.setCurrentIndex(0)
else:
self.setCurrentIndex(1)
def _set_status(self, status):
if status == CardStatus.NoCard:
self.no_key_widget.setText(m.no_key)
elif status == CardStatus.InUse:
self.no_key_widget.setText(m.key_busy)
elif status == CardStatus.Present:
self.no_key_widget.setText(m.key_present)
class YubiOathApplication(qt.Application):
def __init__(self, args):
super(YubiOathApplication, self).__init__(m, version)
QtCore.QCoreApplication.setOrganizationName(m.organization)
QtCore.QCoreApplication.setOrganizationDomain(m.domain)
QtCore.QCoreApplication.setApplicationName(m.app_name)
self.ensure_singleton()
self._widget = None
self.settings = qt.Settings.wrap(
os.path.join(CONFIG_HOME, 'settings.ini'),
QtCore.QSettings.IniFormat)
self._settings = self.settings.get_group('settings')
self._controller = GuiController(self, self._settings)
self._systray = Systray(self)
self._init_systray(args.tray or self._settings.get('systray', False))
self._init_window(not args.tray)
def _init_systray(self, show=False):
self._systray.setIcon(QtGui.QIcon(':/yubioath.png'))
self._systray.setVisible(show)
def _init_window(self, show=True):
self.window.setWindowTitle(m.win_title_1 % self.version)
self.window.setWindowIcon(QtGui.QIcon(':/yubioath.png'))
self.window.resize(self._settings.get('size', QtCore.QSize(320, 340)))
self._build_menu_bar()
self.window.showEvent = self._on_shown
self.window.closeEvent = self._on_closed
self.window.hideEvent = self._on_hide
if show:
self.window.show()
self.window.raise_()
def _build_menu_bar(self):
file_menu = self.window.menuBar().addMenu(m.menu_file)
self._add_action = QtGui.QAction(m.action_add, file_menu)
self._add_action.triggered.connect(self._add_credential)
file_menu.addAction(self._add_action)
self._password_action = QtGui.QAction(m.action_password, file_menu)
self._password_action.triggered.connect(self._change_password)
self._password_action.setEnabled(False)
file_menu.addAction(self._password_action)
settings_action = QtGui.QAction(m.action_settings, file_menu)
settings_action.triggered.connect(self._show_settings)
file_menu.addAction(settings_action)
file_menu.addSeparator()
quit_action = QtGui.QAction(m.action_quit, file_menu)
quit_action.triggered.connect(self._systray.quit)
file_menu.addAction(quit_action)
if sys.platform == "darwin":
close_action = QtGui.QAction(m.action_close, file_menu)
close_action.setShortcut(QtGui.QKeySequence.Close)
close_action.triggered.connect(self.window.hide)
file_menu.addAction(close_action)
help_menu = self.window.menuBar().addMenu(m.menu_help)
about_action = QtGui.QAction(m.action_about, help_menu)
about_action.triggered.connect(self._about)
help_menu.addAction(about_action)
self._controller.refreshed.connect(self._refresh_menu)
def _refresh_menu(self):
enabled = bool(self._controller._reader)
self._password_action.setEnabled(enabled)
def _on_shown(self, event):
if self._settings.get('kill_scdaemon', False):
kill_scdaemon()
if not self._widget:
self._widget = MainWidget(self._controller)
self.window.setCentralWidget(self._widget)
self._controller.refresh_codes()
event.accept()
def _on_hide(self, event):
self._controller.forget_passwords()
event.accept()
def _on_closed(self, event):
self._settings['size'] = self.window.size()
if self._systray.isVisible():
# Unless move is called the position isn't saved!
self.window.move(self.window.pos())
self.window.hide()
event.ignore()
else:
event.accept()
def _libversions(self):
return 'ykpers: %s' % ykpers_version
def _about(self):
QtGui.QMessageBox.about(
self.window,
m.about_1 % m.app_name,
ABOUT_TEXT % (self.version, self._libversions()))
def _add_credential(self):
c = self._controller.get_capabilities()
if c.ccid:
dialog = AddCredDialog(
self.worker,
c.version,
self._controller.get_entry_names(),
parent=self.window)
if dialog.exec_():
if not self._controller._reader:
QtGui.QMessageBox.critical(
self.window, m.key_removed, m.key_removed_desc)
else:
try:
self._controller.add_cred(
dialog.name,
dialog.key,
oath_type=dialog.oath_type,
digits=dialog.n_digits,
algo=dialog.algorithm,
require_touch=dialog.require_touch)
except NoSpaceError:
QtGui.QMessageBox.critical(
self.window, m.no_space, m.no_space_desc)
elif c.otp:
dialog = AddCredLegacyDialog(
self.worker, c.otp, parent=self.window)
if dialog.exec_():
self._controller.add_cred_legacy(dialog.slot, dialog.key,
dialog.touch)
key = 'slot%d' % dialog.slot
self._settings[key] = dialog.n_digits
self._controller.refresh_codes()
else:
QtGui.QMessageBox.critical(self.window, 'No key', 'No key')
def _change_password(self):
dialog = SetPasswordDialog(self.window)
if dialog.exec_():
if not self._controller._reader:
QtGui.QMessageBox.critical(
self.window, m.key_removed, m.key_removed_desc)
else:
self._controller.set_password(dialog.password, dialog.remember)
def _show_settings(self):
if SettingsDialog(self.window, self._settings).exec_():
self._systray.setVisible(self._settings.get('systray', False))
self._controller.settings_changed()
def parse_args():
parser = argparse.ArgumentParser(description='Yubico Authenticator',
add_help=True)
parser.add_argument('-t', '--tray', action='store_true', help='starts '
'the application minimized to the systray')
return parser.parse_args()
def main():
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = YubiOathApplication(parse_args())
sys.exit(app.exec_())
if __name__ == '__main__':
main() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/__main__.py | __main__.py |
from ..core.standard import (YubiOathCcid, TYPE_HOTP)
from ..core.controller import Controller
from ..core.exc import CardError, DeviceLockedError
from .ccid import CardStatus
from yubioath.yubicommon.qt.utils import is_minimized
from .view.get_password import GetPasswordDialog
from .keystore import get_keystore
from . import messages as m
from yubioath.core.utils import ccid_supported_but_disabled
from yubioath.yubicommon.qt import get_active_window, MutexLocker
from PySide import QtCore, QtGui
from time import time
from collections import namedtuple
import sys
if sys.platform == 'win32': # Windows has issues with the high level API.
from .ccid_poll import observe_reader
else:
from .ccid import observe_reader
Code = namedtuple('Code', 'code timestamp ttl')
UNINITIALIZED = Code('', 0, 0)
TIME_PERIOD = 30
INF = float('inf')
class CredEntry(QtCore.QObject):
changed = QtCore.Signal()
def __init__(self, cred, controller):
super(CredEntry, self).__init__()
self.cred = cred
self._controller = controller
self._code = Code('', 0, 0)
@property
def code(self):
return self._code
@code.setter
def code(self, value):
self._code = value
self.changed.emit()
@property
def manual(self):
return self.cred.touch or self.cred.oath_type == TYPE_HOTP
def calculate(self):
window = get_active_window()
dialog = QtGui.QMessageBox(window)
dialog.setWindowTitle(m.touch_title)
dialog.setStandardButtons(QtGui.QMessageBox.NoButton)
dialog.setIcon(QtGui.QMessageBox.Information)
dialog.setText(m.touch_desc)
timer = None
def cb(code):
if timer:
timer.stop()
dialog.accept()
if isinstance(code, Exception):
QtGui.QMessageBox.warning(window, m.error,
code.message)
else:
self.code = code
self._controller._app.worker.post_bg((self._controller._calculate_cred,
self.cred), cb)
if self.cred.touch:
dialog.exec_()
elif self.cred.oath_type == TYPE_HOTP:
# HOTP might require touch, we don't know. Assume yes after 500ms.
timer = QtCore.QTimer(window)
timer.setSingleShot(True)
timer.timeout.connect(dialog.exec_)
timer.start(500)
def delete(self):
if self.cred.name in ['YubiKey slot 1', 'YubiKey slot 2']:
self._controller.delete_cred_legacy(int(self.cred.name[-1]))
else:
self._controller.delete_cred(self.cred.name)
Capabilities = namedtuple('Capabilities', 'ccid otp version')
def names(creds):
return set(c.cred.name for c in creds)
class Timer(QtCore.QObject):
time_changed = QtCore.Signal(int)
def __init__(self, interval):
super(Timer, self).__init__()
self._interval = interval
now = time()
rem = now % interval
self._time = int(now - rem)
QtCore.QTimer.singleShot((self._interval - rem) * 1000, self._tick)
def _tick(self):
self._time += self._interval
self.time_changed.emit(self._time)
next_time = self._time + self._interval
QtCore.QTimer.singleShot((next_time - time()) * 1000, self._tick)
@property
def time(self):
return self._time
class GuiController(QtCore.QObject, Controller):
refreshed = QtCore.Signal()
ccid_disabled = QtCore.Signal()
def __init__(self, app, settings):
super(GuiController, self).__init__()
self._app = app
self._settings = settings
self._needs_read = False
self._reader = None
self._creds = None
self._lock = QtCore.QMutex()
self._keystore = get_keystore()
self._current_device_has_ccid_disabled = False
self.timer = Timer(TIME_PERIOD)
self.watcher = observe_reader(self.reader_name, self._on_reader)
self.startTimer(3000)
self.timer.time_changed.connect(self.refresh_codes)
def settings_changed(self):
self.watcher.reader_name = self.reader_name
self.refresh_codes()
@property
def reader_name(self):
return self._settings.get('reader', 'Yubikey')
@property
def slot1(self):
return self._settings.get('slot1', 0)
@property
def slot2(self):
return self._settings.get('slot2', 0)
@property
def mute_ccid_disabled_warning(self):
return self._settings.get('mute_ccid_disabled_warning', 0)
@mute_ccid_disabled_warning.setter
def mute_ccid_disabled_warning(self, value):
self._settings['mute_ccid_disabled_warning'] = value
def unlock(self, std):
if std.locked:
key = self._keystore.get(std.id)
if not key:
self._app.worker.post_fg((self._init_std, std))
return False
std.unlock(key)
return True
def grab_lock(self, lock=None, try_lock=False):
return lock or MutexLocker(self._lock, False).lock(try_lock)
@property
def otp_enabled(self):
return self.otp_supported and bool(self.slot1 or self.slot2)
@property
def credentials(self):
return self._creds
def has_expiring(self, timestamp):
for c in self._creds or []:
if c.code.timestamp >= timestamp and c.code.ttl < INF:
return True
return False
def get_capabilities(self):
assert self.grab_lock()
ccid_dev = self.watcher.open()
if ccid_dev:
dev = YubiOathCcid(ccid_dev)
return Capabilities(True, None, dev.version)
legacy = self.open_otp()
if legacy:
return Capabilities(None, legacy.slot_status(), (0, 0, 0))
return Capabilities(None, None, (0, 0, 0))
def get_entry_names(self):
return names(self._creds)
def _on_reader(self, watcher, reader, lock=None):
if reader:
if self._reader is None:
self._reader = reader
self._creds = []
if is_minimized(self._app.window):
self._needs_read = True
else:
ccid_dev = watcher.open()
if ccid_dev:
std = YubiOathCcid(ccid_dev)
self._app.worker.post_fg((self._init_std, std))
else:
self._needs_read = True
elif self._needs_read:
self.refresh_codes(self.timer.time)
else:
self._reader = None
self._creds = None
self.refreshed.emit()
def _init_std(self, std):
lock = self.grab_lock()
while std.locked:
if self._keystore.get(std.id) is None:
dialog = GetPasswordDialog(get_active_window())
if dialog.exec_():
self._keystore.put(std.id,
std.calculate_key(dialog.password),
dialog.remember)
else:
return
try:
std.unlock(self._keystore.get(std.id))
except CardError:
self._keystore.delete(std.id)
self.refresh_codes(self.timer.time, lock, std)
def _await(self):
self._creds = None
def wrap_credential(self, tup):
(cred, code) = tup
entry = CredEntry(cred, self)
if code and code not in ['INVALID', 'TIMEOUT']:
entry.code = Code(code, self.timer.time, TIME_PERIOD)
return entry
def _set_creds(self, creds):
if creds:
creds = [self.wrap_credential(c) for c in creds]
if self._creds and names(creds) == names(self._creds):
entry_map = dict((c.cred.name, c) for c in creds)
for entry in self._creds:
cred = entry.cred
code = entry_map[cred.name].code
if code.code:
entry.code = code
elif cred.oath_type != entry_map[cred.name].cred.oath_type:
break
else:
return
elif self._reader and self._needs_read and self._creds:
return
self._creds = creds
self.refreshed.emit()
def _calculate_cred(self, cred):
assert self.grab_lock()
now = time()
timestamp = self.timer.time
if timestamp + TIME_PERIOD - now < 10:
timestamp += TIME_PERIOD
ttl = TIME_PERIOD
if cred.oath_type == TYPE_HOTP:
ttl = INF
if cred.name in ['YubiKey slot 1', 'YubiKey slot 2']:
legacy = self.open_otp()
if not legacy:
raise ValueError('YubiKey removed!')
try:
cred._legacy = legacy
cred, code = super(GuiController, self).read_slot_otp(
cred, timestamp, True)
finally:
cred._legacy = None # Release the handle.
return Code(code, timestamp, TIME_PERIOD)
ccid_dev = self.watcher.open()
if not ccid_dev:
if self.watcher.status != CardStatus.Present:
self._set_creds(None)
return
dev = YubiOathCcid(ccid_dev)
if self.unlock(dev):
return Code(dev.calculate(cred.name, cred.oath_type, timestamp),
timestamp, ttl)
def read_slot_otp(self, cred, timestamp=None, use_touch=False):
return super(GuiController, self).read_slot_otp(cred, timestamp, False)
def _refresh_codes_locked(self, timestamp=None, lock=None, std=None):
if not std:
device = self.watcher.open()
else:
device = std._device
self._needs_read = bool(self._reader and device is None)
timestamp = timestamp or self.timer.time
try:
creds = self.read_creds(device, self.slot1, self.slot2, timestamp,
False)
except DeviceLockedError:
creds = []
self._set_creds(creds)
def refresh_codes(self, timestamp=None, lock=None, std=None):
if not self._reader and self.watcher.reader:
return self._on_reader(self.watcher, self.watcher.reader, lock)
elif is_minimized(self._app.window):
self._needs_read = True
return
lock = self.grab_lock(lock, True)
if not lock:
return
self._app.worker.post_bg((self._refresh_codes_locked, timestamp, lock,
std))
def timerEvent(self, event):
if not is_minimized(self._app.window):
timestamp = self.timer.time
if self._reader and self._needs_read:
self.refresh_codes()
elif self._reader is None:
if self.otp_enabled:
def refresh_otp():
lock = self.grab_lock(try_lock=True)
if lock:
read = self.read_creds(
None, self.slot1, self.slot2, timestamp, False)
self._set_creds(read)
self._app.worker.post_bg(refresh_otp)
else:
if ccid_supported_but_disabled():
if not self._current_device_has_ccid_disabled:
self.ccid_disabled.emit()
self._current_device_has_ccid_disabled = True
event.accept()
return
self._current_device_has_ccid_disabled = False
event.accept()
def add_cred(self, *args, **kwargs):
lock = self.grab_lock()
ccid_dev = self.watcher.open()
if ccid_dev:
dev = YubiOathCcid(ccid_dev)
if self.unlock(dev):
super(GuiController, self).add_cred(dev, *args, **kwargs)
self._creds = None
self.refresh_codes(lock=lock)
def add_cred_legacy(self, *args, **kwargs):
lock = self.grab_lock()
super(GuiController, self).add_cred_legacy(*args, **kwargs)
self._creds = None
self.refresh_codes(lock=lock)
def delete_cred(self, name):
lock = self.grab_lock()
ccid_dev = self.watcher.open()
if ccid_dev:
dev = YubiOathCcid(ccid_dev)
if self.unlock(dev):
super(GuiController, self).delete_cred(dev, name)
self._creds = None
self.refresh_codes(lock=lock)
def delete_cred_legacy(self, *args, **kwargs):
lock = self.grab_lock()
super(GuiController, self).delete_cred_legacy(*args, **kwargs)
self._creds = None
self.refresh_codes(lock=lock)
def set_password(self, password, remember=False):
assert self.grab_lock()
ccid_dev = self.watcher.open()
if ccid_dev:
dev = YubiOathCcid(ccid_dev)
if self.unlock(dev):
key = super(GuiController, self).set_password(dev, password)
self._keystore.put(dev.id, key, remember)
def forget_passwords(self):
self._keystore.forget()
self._set_creds([]) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/controller.py | controller.py |
from __future__ import division
from yubioath.yubicommon.compat import byte2int
from collections import namedtuple
__all__ = ['parse_qr_codes']
Box = namedtuple('Box', ['x', 'y', 'w', 'h'])
def is_dark(color): # If any R, G, or B value is < 200 we consider it dark.
return any(byte2int(c) < 200 for c in color)
def buffer_matches(matched):
return len(matched) == 5 \
and max(matched[:2] + matched[3:]) <= matched[2] // 2 \
and min(matched[:2] + matched[3:]) >= matched[2] // 6
def check_line(pixels):
matching_dark = False
matched = [0, 0, 0, 0, 0]
for (i, pixel) in enumerate(pixels):
if is_dark(pixel): # Dark pixel
if matching_dark:
matched[-1] += 1
else:
matched = matched[1:] + [1]
matching_dark = True
else: # Light pixel
if not matching_dark:
matched[-1] += 1
else:
if buffer_matches(matched):
width = sum(matched)
yield i - width, width
matched = matched[1:] + [1]
matching_dark = False
# Check final state of buffer
if matching_dark and buffer_matches(matched):
width = sum(matched)
yield i - width, width
def check_row(line, bpp, x_offs, x_width):
return check_line([line[i*bpp:(i+1)*bpp]
for i in range(x_offs, x_offs + x_width)])
def check_col(image, bpp, x, y_offs, y_height):
return check_line([image.scanLine(i)[x*bpp:(x+1)*bpp]
for i in range(y_offs, y_offs + y_height)])
def read_line(line, bpp, x_offs, x_width):
matching_dark = not is_dark(line[x_offs*bpp:(x_offs+1)*bpp])
matched = []
for x in range(x_offs, x_offs + x_width):
pixel = line[x*bpp:(x+1)*bpp]
if is_dark(pixel): # Dark pixel
if matching_dark:
matched[-1] += 1
else:
matched.append(1)
matching_dark = True
else: # Light pixel
if not matching_dark:
matched[-1] += 1
else:
matched.append(1)
matching_dark = False
return matching_dark, matched
def read_bits(image, bpp, img_x, img_y, img_w, img_h, size):
qr_x_w = img_w / size
qr_y_h = img_h / size
qr_data = []
for qr_y in range(size):
y = img_y + int(qr_y_h / 2 + qr_y * qr_y_h)
img_line = image.scanLine(y)
qr_line = []
for qr_x in range(size):
x = img_x + int(qr_x_w / 2 + qr_x * qr_x_w)
qr_line.append(is_dark(img_line[x * bpp:(x+1) * bpp]))
qr_data.append(qr_line)
return qr_data
FINDER = [
[True, True, True, True, True, True, True],
[True, False, False, False, False, False, True],
[True, False, True, True, True, False, True],
[True, False, True, True, True, False, True],
[True, False, True, True, True, False, True],
[True, False, False, False, False, False, True],
[True, True, True, True, True, True, True]
]
def parse_qr_codes(image, min_res=2):
size = image.size()
bpp = image.bytesPerLine() // size.width()
finders = locate_finders(image, min_res)
# Arrange finders into QR codes and extract data
for (tl, tr, bl) in identify_groups(finders):
min_x = min(tl.x, bl.x)
min_y = min(tl.y, tr.y)
width = tr.x + tr.w - min_x
height = bl.y + bl.h - min_y
# Determine resolution by reading timing pattern
line = image.scanLine(min_y + int(6.5 / 7 * max(tl.h, tr.h)))
_, line_data = read_line(line, bpp, min_x, width)
size = len(line_data) + 12
# Read QR code data
yield read_bits(image, bpp, min_x, min_y, width, height, size)
def locate_finders(image, min_res):
size = image.size()
bpp = image.bytesPerLine() // size.width()
finders = set()
for y in range(0, size.height(), min_res * 3):
for (x, w) in check_row(image.scanLine(y), bpp, 0, size.width()):
x_offs = x + w // 2
y_offs = max(0, y - w)
y_height = min(size.height() - y_offs, 2 * w)
match = next(check_col(image, bpp, x_offs, y_offs, y_height), None)
if match:
(pos, h) = match
y2 = y_offs + pos
if read_bits(image, bpp, x, y2, w, h, 7) == FINDER:
finders.add(Box(x, y2, w, h))
return list(finders)
def identify_groups(locators):
# Find top left
for tl in locators:
x_tol = tl.w / 14
y_tol = tl.h / 14
# Find top right
for tr in locators:
if tr.x > tl.x and abs(tl.y - tr.y) <= y_tol:
# Find bottom left
for bl in locators:
if bl.y > tl.y and abs(tl.x - bl.x) <= x_tol:
yield tl, tr, bl | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/qrparse.py | qrparse.py |
from .ccid import CardStatus
from yubioath.yubicommon.compat import byte2int, int2byte
from smartcard.scard import (
SCardTransmit, SCardGetErrorMessage, SCardConnect, SCardDisconnect,
SCardEstablishContext, SCardReleaseContext, SCardListReaders,
SCARD_S_SUCCESS, SCARD_UNPOWER_CARD, SCARD_SCOPE_USER, SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0, SCARD_PROTOCOL_T1
)
from PySide import QtCore
import threading
import time
class LLScardDevice(object):
"""
Low level pyscard based backend (Windows chokes on the high level one
whenever you remove the key and re-insert it).
"""
def __init__(self, context, card, protocol):
self._context = context
self._card = card
self._protocol = protocol
def send_apdu(self, cl, ins, p1, p2, data):
apdu = [cl, ins, p1, p2, len(data)] + [byte2int(b) for b in data]
hresult, response = SCardTransmit(self._card, self._protocol, apdu)
if hresult != SCARD_S_SUCCESS:
raise Exception('Failed to transmit: ' +
SCardGetErrorMessage(hresult))
status = response[-2] << 8 | response[-1]
return b''.join(int2byte(i) for i in response[:-2]), status
def __del__(self):
self.close()
def close(self):
SCardDisconnect(self._card, SCARD_UNPOWER_CARD)
SCardReleaseContext(self._context)
class PollerThread(threading.Thread):
def __init__(self, watcher):
super(PollerThread, self).__init__()
self._watcher = watcher
self.daemon = True
self.running = True
def run(self):
old_readers = []
while self.running:
readers = self._list()
added = [r for r in readers if r not in old_readers]
removed = [r for r in old_readers if r not in readers]
self._watcher._update(added, removed)
old_readers = readers
time.sleep(2)
def _list(self):
try:
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if hresult != SCARD_S_SUCCESS:
raise Exception('Failed to establish context : ' +
SCardGetErrorMessage(hresult))
try:
hresult, readers = SCardListReaders(hcontext, [])
if hresult != SCARD_S_SUCCESS:
raise Exception('Failed to list readers: ' +
SCardGetErrorMessage(hresult))
return readers
finally:
hresult = SCardReleaseContext(hcontext)
if hresult != SCARD_S_SUCCESS:
raise Exception('Failed to release context: ' +
SCardGetErrorMessage(hresult))
except:
return []
class CardWatcher(QtCore.QObject):
status_changed = QtCore.Signal(int)
def __init__(self, reader_name, callback, parent=None):
super(CardWatcher, self).__init__(parent)
self._status = CardStatus.NoCard
self.reader_name = reader_name
self._callback = callback or (lambda _: _)
self._reader = None
self._thread = PollerThread(self)
self._thread.start()
def _update(self, added, removed):
if self._reader in removed: # Device removed
self.reader = None
self._set_status(CardStatus.NoCard)
if self._reader is None:
for reader in added:
if self.reader_name in reader:
self.reader = reader
self._set_status(CardStatus.Present)
return
@property
def status(self):
return self._status
def _set_status(self, value):
if self._status != value:
self._status = value
self.status_changed.emit(value)
@property
def reader(self):
return self._reader
@reader.setter
def reader(self, value):
self._reader = value
self._callback(self, value)
def open(self):
if self._reader:
try:
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if hresult != SCARD_S_SUCCESS:
raise Exception('Failed to establish context : ' +
SCardGetErrorMessage(hresult))
hresult, hcard, dwActiveProtocol = SCardConnect(
hcontext, self._reader,
SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1)
if hresult != SCARD_S_SUCCESS:
raise Exception('Unable to connect: ' +
SCardGetErrorMessage(hresult))
return LLScardDevice(hcontext, hcard, dwActiveProtocol)
except Exception:
self._set_status(CardStatus.InUse)
def __del__(self):
self._thread.running = False
self._thread.join()
def observe_reader(reader_name='Yubikey', callback=None):
return CardWatcher(reader_name, callback) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/ccid_poll.py | ccid_poll.py |
from __future__ import division
__all__ = ['decode_qr_data']
def decode_qr_data(qr_data):
"""Given a 2D matrix of QR data, returns the encoded string"""
size = len(qr_data)
version = (size - 17) // 4
level = bits_to_int(qr_data[8][:2])
mask = bits_to_int(qr_data[8][2:5]) ^ 0b101
read_mask = [x[:] for x in [[1]*size]*size]
# Verify/Remove alignment patterns
remove_locator_patterns(qr_data, read_mask)
remove_alignment_patterns(read_mask, version)
remove_timing_patterns(read_mask)
if version >= 7: # QR Codes version 7 or larger have version info.
remove_version_info(read_mask)
# Read and deinterleave
buf = bits_to_bytes(read_bits(qr_data, read_mask, mask))
buf = deinterleave(buf, INTERLEAVE_PARAMS[version][level])
bits = bytes_to_bits(buf)
# Decode data
buf = ''
while bits:
data, bits = parse_bits(bits, version)
buf += data
return buf
LOCATOR_BOX = [
[1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]
]
MASKS = [
lambda x, y: (y+x) % 2 == 0,
lambda x, y: y % 2 == 0,
lambda x, y: x % 3 == 0,
lambda x, y: (y+x) % 3 == 0,
lambda x, y: (y/2 + x/3) % 2 == 0,
lambda x, y: (y*x) % 2 + (y*x) % 3 == 0,
lambda x, y: ((y*x) % 2 + (y*x) % 3) % 2 == 0,
lambda x, y: ((y+x) % 2 + (y*x) % 3) % 2 == 0
]
ALPHANUM = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
EC_LEVELS = ['H', 'Q', 'M', 'L']
INTERLEAVE_PARAMS = [ # From ISO/IEC 18004:2006
[], # H, Q, M, L
[1 * (9,), 1 * (13,), 1 * (16,), 1 * (19,)], # Version 1
[1 * (16,), 1 * (22,), 1 * (28,), 1 * (34,)],
[2 * (13,), 2 * (17,), 1 * (44,), 1 * (55,)],
[4 * (9,), 2 * (24,), 2 * (32,), 1 * (80,)],
[2 * (11,) + 2 * (12,), 2 * (15,) + 2 * (16,), 2 * (43,), 1 * (108,)],
[4 * (15,), 4 * (19,), 4 * (27,), 2 * (68,)],
[4 * (13,) + 1 * (14,), 2 * (14,) + 4 * (15,), 4 * (31,), 2 * (78,)],
[4 * (14,) + 2 * (15,), 4 * (18,) + 2 * (19,), 2 * (38,) + 2 * (39,), 2 * (97,)], # noqa: E501
[4 * (12,) + 4 * (13,), 4 * (16,) + 4 * (17,), 3 * (36,) + 2 * (37,), 2 * (116,)], # noqa: E501
[6 * (15,) + 2 * (16,), 6 * (19,) + 2 * (20,), 4 * (43,) + 1 * (44,), 2 * (68,) + 2 * (69,)], # noqa: E501
[3 * (12,) + 8 * (13,), 4 * (22,) + 4 * (23,), 1 * (50,) + 4 * (51,), 4 * (81,)], # noqa: E501
[7 * (14,) + 4 * (15,), 4 * (20,) + 6 * (21,), 6 * (36,) + 2 * (37,), 2 * (92,) + 2 * (93,)], # noqa: E501
[12 * (11,) + 4 * (12,), 8 * (20,) + 4 * (21,), 8 * (37,) + 1 * (38,), 4 * (107,)], # noqa: E501
[11 * (12,) + 5 * (13,), 11 * (16,) + 5 * (17,), 4 * (40,) + 5 * (41,), 3 * (115,) + 1 * (116,)], # noqa: E501
[11 * (12,) + 7 * (13,), 5 * (24,) + 7 * (25,), 5 * (41,) + 5 * (42,), 5 * (87,) + 1 * (88,)], # noqa: E501
[3 * (15,) + 13 * (16,), 15 * (19,) + 2 * (20,), 7 * (45,) + 3 * (46,), 5 * (98,) + 1 * (99,)], # noqa: E501
[2 * (14,) + 17 * (15,), 1 * (22,) + 15 * (23,), 10 * (46,) + 1 * (47,), 1 * (107,) + 5 * (108,)], # noqa: E501
[2 * (14,) + 19 * (15,), 17 * (22,) + 1 * (23,), 9 * (43,) + 4 * (44,), 5 * (120,) + 1 * (121,)], # noqa: E501
[9 * (13,) + 16 * (14,), 17 * (21,) + 4 * (22,), 3 * (44,) + 11 * (45,), 3 * (113,) + 4 * (114,)], # noqa: E501
[15 * (15,) + 10 * (16,), 15 * (24,) + 5 * (25,), 3 * (41,) + 13 * (42,), 3 * (107,) + 5 * (108,)], # noqa: E501
[19 * (16,) + 6 * (17,), 17 * (22,) + 6 * (23,), 17 * (42,), 4 * (116,) + 4 * (117,)], # noqa: E501
[34 * (13,), 7 * (24,) + 16 * (25,), 17 * (46,), 2 * (111,) + 7 * (112,)],
[16 * (15,) + 14 * (16,), 11 * (24,) + 14 * (25,), 4 * (47,) + 14 * (48,), 4 * (121,) + 5 * (122,)], # noqa: E501
[30 * (16,) + 2 * (17,), 11 * (24,) + 16 * (25,), 6 * (45,) + 14 * (46,), 6 * (117,) + 4 * (118,)], # noqa: E501
[22 * (15,) + 13 * (16,), 7 * (24,) + 22 * (25,), 8 * (47,) + 13 * (48,), 8 * (106,) + 4 * (107,)], # noqa: E501
[33 * (16,) + 4 * (17,), 28 * (22,) + 6 * (23,), 19 * (46,) + 4 * (47,), 10 * (114,) + 2 * (115,)], # noqa: E501
[12 * (15,) + 28 * (16,), 8 * (23,) + 26 * (24,), 22 * (45,) + 3 * (46,), 8 * (122,) + 4 * (123,)], # noqa: E501
[11 * (15,) + 31 * (16,), 4 * (24,) + 31 * (25,), 3 * (45,) + 23 * (46,), 3 * (117,) + 10 * (118,)], # noqa: E501
[19 * (15,) + 26 * (16,), 1 * (23,) + 37 * (24,), 21 * (45,) + 7 * (46,), 7 * (116,) + 7 * (117,)], # noqa: E501
[23 * (15,) + 25 * (16,), 15 * (24,) + 25 * (25,), 19 * (47,) + 10 * (48,), 5 * (115,) + 10 * (116,)], # noqa: E501
[23 * (15,) + 28 * (16,), 42 * (24,) + 1 * (25,), 2 * (46,) + 29 * (47,), 13 * (115,) + 3 * (116,)], # noqa: E501
[19 * (15,) + 35 * (16,), 10 * (24,) + 35 * (25,), 10 * (46,) + 23 * (47,), 17 * (115,)], # noqa: E501
[11 * (15,) + 46 * (16,), 29 * (24,) + 19 * (25,), 14 * (46,) + 21 * (47,), 17 * (115,) + 1 * (116,)], # noqa: E501
[59 * (16,) + 1 * (17,), 44 * (24,) + 7 * (25,), 14 * (46,) + 23 * (47,), 13 * (115,) + 6 * (116,)], # noqa: E501
[22 * (15,) + 41 * (16,), 39 * (24,) + 14 * (25,), 12 * (47,) + 26 * (48,), 12 * (121,) + 7 * (122,)], # noqa: E501
[2 * (15,) + 64 * (16,), 46 * (24,) + 10 * (25,), 6 * (47,) + 34 * (48,), 6 * (121,) + 14 * (122,)], # noqa: E501
[24 * (15,) + 46 * (16,), 49 * (24,) + 10 * (25,), 29 * (46,) + 14 * (47,), 17 * (122,) + 4 * (123,)], # noqa: E501
[42 * (15,) + 32 * (16,), 48 * (24,) + 14 * (25,), 13 * (46,) + 32 * (47,), 4 * (122,) + 18 * (123,)], # noqa: E501
[10 * (15,) + 67 * (16,), 43 * (24,) + 22 * (25,), 40 * (47,) + 7 * (48,), 20 * (117,) + 4 * (118,)], # noqa: E501
[20 * (15,) + 61 * (16,), 34 * (24,) + 34 * (25,), 18 * (47,) + 31 * (48,), 19 * (118,) + 6 * (119,)], # noqa: E501
]
ALIGNMENT_POSITIONS = [ # From ISO/IEC 18004:2006
[],
[],
[18], # Version 2
[22],
[26],
[30],
[34],
[6, 22, 38],
[6, 24, 42],
[6, 26, 46],
[6, 28, 50],
[6, 30, 54],
[6, 32, 58],
[6, 34, 62],
[6, 26, 46, 66],
[6, 26, 48, 70],
[6, 26, 50, 74],
[6, 30, 54, 78],
[6, 30, 56, 82],
[6, 30, 58, 86],
[6, 34, 62, 90],
[6, 28, 50, 72, 94],
[6, 26, 50, 74, 98],
[6, 30, 54, 78, 102],
[6, 28, 54, 80, 106], # Version 24
[6, 32, 58, 84, 110],
[6, 30, 58, 86, 114],
[6, 34, 62, 90, 118],
[6, 26, 50, 74, 98, 122],
[6, 30, 54, 78, 102, 126],
[6, 26, 52, 78, 104, 130],
[6, 30, 56, 82, 108, 134],
[6, 34, 60, 86, 112, 138],
[6, 30, 58, 86, 114, 142],
[6, 34, 62, 90, 118, 146],
[6, 30, 54, 78, 102, 126, 150],
[6, 24, 50, 76, 102, 128, 154],
[6, 28, 54, 80, 106, 132, 158],
[6, 32, 58, 84, 110, 136, 162],
[6, 26, 54, 82, 110, 138, 166],
[6, 30, 58, 86, 114, 142, 170]
]
def check_region(data, x, y, match):
"""Compares a region to the given """
w = len(match[0])
for cy in range(len(match)):
if match[cy] != data[y+cy][x:x+w]:
return False
return True
def zero_region(data, x, y, w, h):
"""Fills a region with zeroes."""
for by in range(y, y+h):
line = data[by]
data[by] = line[:x] + [0]*w + line[x+w:]
def bits_to_int(bits):
"""Convers a list of bits into an integer"""
val = 0
for bit in bits:
val = (val << 1) | bit
return val
def bits_to_bytes(bits):
"""Converts a list of bits into a string of bytes"""
return ''.join([chr(bits_to_int(bits[i:i+8]))
for i in range(0, len(bits), 8)])
def bytes_to_bits(buf):
"""Converts a string of bytes to a list of bits"""
return [b >> i & 1 for b in map(ord, buf) for i in range(7, -1, -1)]
def deinterleave(data, b_cap):
"""De-interleaves the bytes from a QR code"""
n_bufs = len(b_cap)
bufs = []
for _ in range(n_bufs):
bufs.append([])
b_i = 0
for i in range(sum(b_cap)):
b = data[i]
while b_cap[b_i] <= len(bufs[b_i]):
b_i = (b_i + 1) % n_bufs
bufs[b_i].append(b)
b_i = (b_i + 1) % n_bufs
buf = ''
for b in bufs:
buf += ''.join(b)
return buf
def parse_bits(bits, version):
"""
Parses and decodes a TLV value from the given list of bits.
Returns the parsed data and the remaining bits, if any.
"""
enc, bits = bits_to_int(bits[:4]), bits[4:]
if enc == 0: # End of data.
return '', []
elif enc == 1: # Number
n_l = 10 if version < 10 else 12 if version < 27 else 14
l, bits = bits_to_int(bits[:n_l]), bits[n_l:]
buf = ''
while l > 0:
if l >= 3:
num, bits = bits_to_int(bits[:10]), bits[10:]
elif l >= 2:
num, bits = bits_to_int(bits[:7]), bits[7:]
else:
num, bits = bits_to_int(bits[:3]), bits[3:]
buf += str(num)
elif enc == 2: # Alphanumeric
n_l = 9 if version < 10 else 11 if version < 27 else 13
l, bits = bits_to_int(bits[:n_l]), bits[n_l:]
buf = ''
while l > 0:
if l >= 2:
num, bits = bits_to_int(bits[:11]), bits[11:]
buf += ALPHANUM[num // 45]
buf += ALPHANUM[num % 45]
l -= 2
else:
num, bits = bits_to_int(bits[:6]), bits[6:]
buf += ALPHANUM[num]
l -= 1
return buf, bits
elif enc == 4: # Bytes
n_l = 8 if version < 10 else 16
l, bits = bits_to_int(bits[:n_l]), bits[n_l:]
return bits_to_bytes(bits[:l*8]), bits[l*8:]
else:
raise ValueError('Unsupported encoding: %d' % enc)
def remove_locator_patterns(data, mask):
"""
Verifies and blanks out the three large locator patterns and dedicated
whitespace surrounding them.
"""
width = len(data)
if not check_region(data, 0, 0, LOCATOR_BOX):
raise ValueError('Top-left square missing')
zero_region(mask, 0, 0, 9, 9)
if not check_region(data, width-7, 0, LOCATOR_BOX):
raise ValueError('Top-right square missing')
zero_region(mask, width-8, 0, 8, 9)
if not check_region(data, 0, width-7, LOCATOR_BOX):
raise ValueError('Bottom-left square missing')
zero_region(mask, 0, width-8, 9, 8)
def remove_alignment_patterns(mask, version):
"""Blanks out alignment patterns."""
positions = ALIGNMENT_POSITIONS[version]
for y in positions:
for x in positions:
# Do not try to remove patterns in locator pattern positions.
if (x, y) not in [(6, 6), (6, positions[-1]), (positions[-1], 6)]:
zero_region(mask, x-2, y-2, 5, 5)
def remove_timing_patterns(mask):
"""Blanks out tracking patterns."""
width = len(mask)
mask[6] = [0] * width
for y in range(width):
mask[y][6] = 0
def remove_version_info(mask):
"""Removes version data. Only for version 7 and greater."""
width = len(mask)
zero_region(mask, width-11, 0, 3, 6)
zero_region(mask, 0, width-11, 5, 6)
def read_bits(qr_data, read_mask, mask):
"""Reads the data contained in a QR code as bits."""
size = len(qr_data)
mask_f = MASKS[mask]
bits = []
# Skip over vertical timing pattern
for x in reversed(list(range(0, 6, 2)) + list(range(7, size, 2))):
y_range = range(0, size)
if (size - x)/2 % 2 != 0:
y_range = reversed(y_range)
for y in y_range:
for i in reversed(range(2)):
if read_mask[y][x+i]:
bits.append(qr_data[y][x+i] ^ mask_f(x+i, y))
return bits | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/qrdecode.py | qrdecode.py |
# Resource object code
#
# Created: tis nov 22 13:28:33 2016
# by: The Resource Compiler for PySide (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = b"\x00\x00\x01n\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x14\x00\x00\x00\x14\x08\x06\x00\x00\x00\x8d\x89\x1d\x0d\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xdf\x06\x03\x09\x16&s\x0dU\xb1\x00\x00\x00\x19tEXtComment\x00Created with GIMPW\x81\x0e\x17\x00\x00\x00\xd6IDAT8\xcb\xbd\x94Q\x11\xc20\x0c\x86\xbf\xdb!\x00\x09\x93P\x09\x95\x80\x84I@\x02(\x98\x84\xe2d\x126\x098(\x0e\xe0\xa5\xbb\x0b!Mw\xdc wyj\xfa%i\xfe\x14\xfelG \xee\x01\xea\x81\x04<\x8bK\xe8\xa4<\x01'\x0f6\x08\x90\x05\xd4gs\xe9\xa4\x09\xcb\xc0\xa5T\x8b\x03<{mf\x01\x0b\x958\x0d\xccFR\x10o\xe6\xc1\x101\xb2\x9bd\x05\xae\xd5\x8d\x8d\x81\xc9\x84\xa3H\xf0fQd\x0b\x1b\x14\xb0Z\xd0\x83\xeb\x8c\x0bK\x03x\xf7b\xbb\xbd7\xc1\x02\x86J{4b\x9bC\x09\xd6c+\xab\x0e\x05\xb5j\x83H\xe0U\xe7\xcaF\x0a[z\x0d\x96[\xc2\xa6\xac\x91\x07\xec\xcb:f\xd5M\xf5\xab\x9a\x1d`4\xce>`\x07ua\x01\x1e\x1b\xd4q\x03\xaeJ\x93_Y\xf4\xbe\xaa\x9f\xd8\x0b\x80^c2\x88\xe5\xdbg\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00U\xc4\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x80\x00\x00\x00\x80\x08\x06\x00\x00\x00\xc3>a\xcb\x00\x00\x00\x06bKGD\x00\xf6\x00\xf6\x00\xf6\xdb\xa0F\xc9\x00\x00\x00\x09pHYs\x00\x00.#\x00\x00.#\x01x\xa5?v\x00\x00\x00\x07tIME\x07\xdd\x08\x1e\x0a-5\x99\xcc\xd5&\x00\x00 \x00IDATx\xda\xec\xbdy\x90e\xd9Y'\xf6;\xe7\xaeo_2_f\xe5RYU]\x8b\xba\xab\x17-\xadn`\x8c\x84D\x0b\x09f<\xe3@&\xd0D\xb0\xd8a\x06G\xe0\x08\x07D\xcc?6\x86\x88\x81\x19a@\xfe\xc34\x22d\x03\x11\xc2CG\xa8\x99f `\x02\x09\xbb\x85\x10\x18\x09\xab\xe9\xee\xea\xee\xea\xea\xaa\xac\xae=3+\xd7\xb7\xafw;\xc7\x7f\x9c\xe5\x9e\xfb\xde\xab\xae\x96\xd4\x08\x09;+n\xe4\xab\x97o\xb9\xf7\x9e\xef|\xeb\xef\xfb}\x04\xffx\x7f\xc8=\x1e\x7f=?\xfc\x1e\x8f\xffQ\xde\xa4\x7fL\x8b\xad\x0e\x10B(\xe7\x9cL\xfd\xed~\x8b>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\x97\xb1\xb6\xb6\x86\x8d\x8d\x0d\xac\xad\xafa\xa9\xb1\x84J\xa5\x8aB!\x0f\xd7\xf5`\xdb\xb3\x80\x10\x9e0$\x9c\x81R\x9a\x22\x822\xb5\x81\xe9+\xe1\xe0f\xbd'\x93\x89\xe7\xba\x18ej\x06-:22q]\x17\xb9\x9c\x8fB!\x8fr\xb9\x8cf\xb3\x85\xdd\xbd]\x0c\x06}\x04A\x88\xe1p\x88\xe5\xe5e\x94J%\xb8\xae\x8b$N\xc0\x01X\x16\x85\xeb\xba\xc8\x17\x0a(\x97\xcb\xe0\x9c\xc3\xf7<\x95*\xc6h4B\x14E\xc8\xe5D\x09{qqq\xe3\xc7~\xec\xc7\xfe\xd53\xcf<\x13\xde\xbd{7$\x84$\x9c\xf3\xc4H\x1a}k4\x80eY4\x0cC\x07@\xf9K_\xfa\xd2\x7f\xb7\xba\xb6\xf6\xaf:\x9d\x8e\xd3\xebv\xc190\x1a\x09g\xcf\xf7}\x0c\x07\x03\xec\xed\xedakk\x0b\xcdf\x13Q\x18!\x8a#\xec\xed\xed\xe1+_\xf9\x0a\xde\xf7\xbe\xf7\xa1X,\xe2\xcb_\xfe2\xfe\xe4O\xfe\x04\x9b\x9b\x9bp\x1c\x07\xab\xab\xabx\xe8\xa1\x87p\xfe\xfcC8s\xe6,\x8eo\x1c\x97\x02 \x922\xae+v\x15\xa1\x144-\x22dj\xf4\xd3\x99837\x9f=X\xc61T\xa9\x5c\x81(\x82\xb4\xe3l\x06g\xa0r\x0b\x84\x10\xa9\xeeE\xa8\x99\xcb\xf9p\x1c\x17\x83A\x1f\xedv\x07a\x14\xe9\xf78\x8e\x838\x8eQ,\x16A\x08A\xab\xdd\xc6\xce\xf66\xb6\xb6\xb7\xd0\xef\xf7\xc1\x18C\x10\x86x\xf5\xd5W\xb1\xb3\xb3\x83\xb3g\xcff\xfc\x19\xd7u\x97j\xb5Z\xf1\xea\xd5\xab[a\x18\x0ed~ \xfaFq\x05\xdf\x88\x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a0R\xa9\xac\xac\xaf\xaf\x9f\x03P\x95f\xc0\x9a^s:\xa7\xeaG\x9e~\xfa\xe9\xf7[\x16]\xeft:\x22\xf5\x99q8\x98V\xd7\x5cW\xcd8\x82 \xc0\xd5\xabW\x11\x04\x01\xf2\xf9<\x96\x97\x97E\x0f]!\xaf\xbd\xfei\xdb\xc9\x98\x81\xc5\x9f\xfa\x9b\xb2\xfb\xae\xe7\xa1V\xadI\xc1\x82.\xb6d\x16D;\x81\xe6{\x85\x19X^^F\xb9T\xc2Q\xb3)@\x96\x863\x98\x82?\xb8^\xd4 \x08\xb4W\xee\xban\xf6\x9c\xe49+\xda\xb84\xf1#`\xdd\xb7n\xddB\x18\x85\xa8V+(\x16\x0b\xf0<Of\x07\xa9nh%\x84\xce\x0a\x01\xa5\xba\x0d\xce\xa2\x224t]W;\xa1\x07\x07\x07\x22\x19e\xd9\xa2\xc8\xc4SAg<\xc9D`\x09K\x9b^\x8b\xc5b\xbd\xb1\xd48)\x05\xa0`\xf8\x01d\xae\x06p]\x97\x00 'N\x9cx\x94q\xbe\xd6\xef\xf53\x17\xcfg\xe2O\x85\xba%888\x80\x82\x865\x1a\x0d,6\x1a(\x97\xcb\xf0\x5cW'\x8c2^\xbfi\x06\x12\xc5\xbd\x97\x0a\x86ZH\xdb\xb6Q(\x16\x10\x04\x81\xc8\xcc\xa9D\x8c\x19\x86%\x0bu\xfe.\x00\x00 \x00IDATlF\x88\xc09r\xbe/\x90E\xc5\xa2n\xe6\x88\xc2h\xa6`d6\x83DQ\x04\xdb\xb6\xe0\xfb>(\xa5\xd9]\xcf\xe7\x87\x7f\xa3\xf1\x08Q\x14\xe2\xd2\xa5Kb\xf7\x97\x8a\xc8\xe5s\x99\xdd?\xdd\x9fp/! \xd2\x1cX\x96\x05\xcf\xf3P.\x975\x80$\x97\xcf\xa7\xa9j6\xab\x01\x04v\x91\xa9\x0a!\xf2\xf9\xbcS)W\xd6d4P\x84\xe0d\xba\xa7\x0f@\xc20\xa4\xf9|a\xa1Z\xad>\x18\x04\x813\x9eL\xb4\x8d\x9b\xbe\xc1\xa9:b\x88\x13\x91\xc1\x1a\x8fEs\xc3\xe2\xe2\x22\xaa\xd5\xaa\x90`\xdbJ\xdb\xa4\xd8T\xce\xc0\x08\xe3\xb4F\x90q\xb6\xe9\x0cz\xae\x87B\xa1\x80v\xa7#\xea\xefJk$\xf3\x84'\xfd\x5c\xc7\x11\xfd\x82\x8b\x8b\x8b \x84\xa0\xd3\xe9\xea\x9c\x80\xce9\x18\x5c\xc1a\x18\x02D\xb0x\xf8\xbe\xaf\x8bS\x19\xb5?\x95\x03\x88\xe3\x18\xa3\xe1\x08\x07\x07\xfb\x18\x8dF\xa2K\xa9X\x82\xefe;\x94\xder\xd1\x09\x81\xa5\x93ED'\x87\x04\xc28\xa7;\x92\xca\xe5\xb26IY\xf4R\xea\x1b0\x99\x1f \xf2:\xca\x95\xca\xb1z\xbd\xbe&\x1d\xc1\x99\xa4\xd0\xb4\x09 ?\xff?\xfd\x8f\x0f\xf8\xbe\x7f\xba\xdf\xef#2l&3\xec>\xcb\xd4\xe1\x81\xc1p\x88\xbd\xbd=\x8cF#\x94\xcbe,,,\x88\xdd\xefy\xba\x0c\xca\x98\xec\xbf3J\xbai\xfd\xdc\xd8\xf5zq\x13\x1d\xb69\xae\x83b\xb1\x84\xe1` \x920\xaa<\xcc\xc4\x91\xd1\x02\x86Y \x94\xa0P(`ee\x05\x94R\xb4\xdb-\xddW\x98V\xee\xd2~\xff\xc9d\xa2=\x7f\xc7q\xc4u&S\x8b\xcf\xb2l\xa1\xe3\xb1HY_\xba\xf4\x86\xec .\xa1\x90/\xc0\x93\x15Nk\xca\xc9\xa3\x19?@\x98\x05K\x99\x00C(,C\x0b\x14\x0a\x05look\x98\x5c\xc6\x04\x1a\x8bo\xb6\xa7\xab\xa6\xdar\xa9\xb4X\xadVW\xa4#h\x0a\x001k\x01\xea\x09\xeb\xec\xe9\xd3'-\xcb:1\x18\x0e\x11'IZ\x80 \x00\xe5\xf2eD\xe4\xff98,N\xd0j6\xb5\x93\xa6\x1a5\x95\xfdR\xbb\x88\x92\x14!\xa4y\xf5\x04\x85\x12(%`\x84\x00\x84\x81\xcb\xe79\xa7\x12o nX.'\xba|{\xdd\x9e\xc4\xd4'i\xb7\x0f\x01\x12B@bdz\xf6\xa5\x1aD\xb5ZE\xb5Z\xc5\xd1\xd1\x11\xfa\xfd>\x0a\x85\x02|\xdf\xcf8wq\x1c\x09x\x9b\x95\xaa\xffD\x81;\x92$\xd3;h\xfe\x1e\x8dF\xe8v\xbb8<<\xc4\xb1c\xc7P*\x95\xb5\xfaW\xa4\x96&\x01F&\x0c\xc4\x14;\x8afE\x93\xf48\xb2\xe8\xe6\xfb>z\xdd\xae\xf6\x0bz\xbd\x9eNde\xb8\x8bLP+\x00\x8bR\x94J\xa5B>\x9foH\x01\x98\xc9\x07\xd8\x06\xa6\x9d0\xc6h\xa9\x5cY\x05\xb08\x1e\x8f\xc1\x92\x04\x9a\xa9\x8b\x03Lu\xcap\x02N\xb8\xbe\xd9G\x87\x87\x98\x8c\xc7\xb0m\x1b\xd5\xaa\xe8\xcfS\xb6_\xa7|\x91\xc8\xf7\xa5\x17\xcd\x19D\x05\x90\x13@\xc6\xc4\xa0\x04\x9c\x13\x9d-TdP\xae\xe3\x0a3\xd0n#\x97\xcf\x83\xc7\x91\x01\xf4\xb0\x01H\xe2\x89\x84\x81\xd0\x04\x94Q$I\x22\xb3k\x22+(j\x03]T\xabU8\xd21M\xa4\x09\x09CQ~vd\x18&\xea\x0f\x09\x98l\x10M\xe4\xe3\xc4\x10\x00\xe1\x97\x84\xb8z\xf5\xaa\xf6\xda\x8b\x85\x02|\xa9A\xa6\xbb\x92\xcd\x96wh\xc63\xa2\x89\xb12\xdcGr\xa3\x88d\x94\x870\x0c\xd1\xeb\xf5D\x1f\xe5>2\xd8\xc4Le\xc3(;\xabRu\xb1TZ\xa2\x96UgI\x927\xf2\x01\x0c\x00\xb7\x8d\xda=\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x1eg\xfb\x14\x09\x99y\xac\xfc\x8fB\xa1Pu=\xb7\x8a>\xf2S\x09!\x92\x11\x80s\xe7\xce\xd6=\xcf]\xef\xf5\xfa\xb2\xd3\x87\x09\xa8\x97ag\x88\xc1\xc3\xcf\x00\x0c\xfa\x03\x84A\xa8\xd8\xae\x8c\xddO\xb5C\x02B\x90\xc8\x8b\xe4\x9a\xdcqZ\xf2E\xeb\x93\xb2\x8b\xcaA\x146T\xda4\xdbB\xce\xf71\x18\x0c0\x09\x02x\x0a.>\x05M\x22H\x1d\xad$I\xe0y\x1e\xaa\xd5*6Nl\xe0\xea\x9bW\xd1\xedvQ.Wt\xebz\x10\x04\x88\xa3\x18\x85BA\x17~\xe2X\xcc\x07H\x0c\x13`\xda\xfe\xc9d\x82(\x8ap\xe7\xce\x1d\xa1\xfe\xab\x15a\xfar\xbeH\xfd\x9a\xea\xdf \xb4\x9c\xb6\xf3\x80\xf2\x07\x90\x99u\xa0\xe8p\x99\xacI\xb8\xae\x8bP\x86\xb0\xf9|\x1e\x9dN\xc7`S3\xfa\x9c5\x89\xa6\xf8\x1c\xdb\xb6Q\xc8\x17*\xae\xe3Vd.\xc01\x1cAn&\x06\xacj\xb5V\xb7,ge2\x91\xfc}\x84\x80\xc8\xd4*\xa6\xed\xb2t\xeeF\xa3!\x82 \x80m\xdb\x92t\xd9\xd7\xe9S\xce8\x18R3\xc2\x15t+\x967@\xae\xac\x96~SCpS\x10\x88\x86A+\xe4\xf0h4\x04\xa5E\xf9\x1a'\x93\xd8\x17\xbb?\xd2P)\x879\xa8\xd7\xeb(\x14\x0a\xa8\xd5j\xe8\xf5\x04\x89\x94-\xeb\xed\xc2\xfe3x\x9e0\x0bI\x92.~\x14E3\x8b\xafL\xc6\xde\xfe\x1e\xa28Bc\xb1\x81J\xb9\x82|!'XI,Gg\x13\xc9\x94\xd93\xb5^\xc6\xe1\x13\xdb+\x15\x0c\xa20{\xb6\xca\xd1\x08_E&\xda,\xdb\x12V\x9c #4\xc4D\x1fKH~.\x9fsl\xdb.\x02\xc8\xcb\x5c\x00\x9d\x8e\x02\x00\xc0r]\xb7\x08\xf0J\x10\x08\xfb\xafT\x928o\xae\xe8\xed\xc4B\x0a\xff\x1e\x93\x89p\x84\x14q\x82\xe3:\xa9\x80p\x06\xca\xa8!\x04)\xf5+\x91&\x84\x00`\x94\xde\x13\xeb\xc7\x19\xd3\xb1\xb2\x08\x09\x05\xdfO\xbf\xdf\x17\xcd\x16\xca?\x91\xa1\xaa\x93\xd9e\x02\xbe\x16\xd9\x11\xf2\x85<J\xc5\x12\x96\x97\x97q\xe9\xd2%\xf4\xba]x\xf2\xfd\x93I\xa0\xeb\xf6\x0aS\x18\xc5\xc2,$\x06S\x88\x0a1\x15m\xcc\xee\xdd]\xd8\x96\xad\x99A\x14-\x0d\x9dCFa\x12_fy\x11S\x95\x9f\xde\x1f\x22\x91\xd5*}.r\x02\x93\xc9\x04A\x18\x88\xfbl;\xba\x994eV\xcd\x12\xbf\x10B\xb4\xf9p]\xb7,5\x80gF\x02\xb6\x02\xfes\xce\xa9\x1c\xb0\xe4\x07A \x93\x09\x1cl\x9a\xafWv\xad(\x1b;\x91M\x8d\xb9\x5cN\xefN\x15\x1d\x10J2\xfdr\xd3\xbf\xb5\x1d\x9c\x22\x88V&\x81A\xee\x22\xc64v\x90\xca\x1ay\xbf/\xb8~\x95`\xd96\xcb\x02>\xe4\xcd\xb5,\x8a8\x8c\xe0\xb9\x1e\x1a\xcbK8vl\x05\xaf\xbf\xfe:\xba\xdd.\xfc\x9c\x0f\x02\x82 \x98 \x9f\xafi\xe7\xcfd\x0a\x9b\xab\xfe\x03\x01;\xebv\xbb\xc8\xe7\x0b\xa8V\xab\xa2\xf2\xe7\x8aV6MPA\x08(\xc9\xd2\xdb\xce\xdc\x07\xccR\xdeN\x93Z\xd8$\x05\xa3\xc6q\x82R\xa9 5\x15K\xdb\x1fu\xf3\xc9\x94\x00\xc8\xf5\xa8T*u\xc7q\xf2Q\x14\xb9f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2\x10:Y\x04\x92\x11\x840\x0c\xb1\xbf\xbf\x8f\xc9x\x0c\x00XYYA\xa3\xb1\x88r\xb9\x04\xdf\xcf\xc1\xb2\xa8N|\xcd\x90:\x99\x18\xbd\xfb\x08\xc5\xccc\xa9\x12\xa63\x85\xca\x9fI\x92XWImJQ\x93\xa6M\xc1\xda<\xd7\x85e; \x04\x18\x8f\xc72\x85\x1d\x85\x8c\xb1i\x86qn\x1bz\x87O\xc6\xe3A\x1cE\x89\xe38\x16g\xa9\x87\xea\xfb\xbe\xa4,\x15\x0e\x8b\xb2G\xea\xa4\xfc\x9c\x8f\xc1p\x80 \x0c\x10\x86\x22\x99\xa2\x86>\xdd\xebB\xd3]\xce\x0dz7\x96\xe1\xea\x99\xe1\xede\x10\x13>\xe6t\xe8\xa8n\xdbv\xbb\x8d\x85\x85\x05P\xc9\xc4m\xce\x0c2\x19\xc8DN=\x9d\x03\xa0\xfb\x065\xb5\x9d@\xe0\x1cHF\xb4\xc5\xc5E,//\xa3V\xab\x8b\x96/\xd7\x95\xd5Nd:\x93M\x7f\x85\x01\xb3\xac\x1e\x0a[9-\x04R-\x99\xfd\x8d&_\xa0\x0a\xffr\xb9\x9cn\xd6Q]E\x1c\x1c\x0e\xa5\x06\x09\x86\xca\x1dPDQ\x88(\x8a0\x1c\x0e\x07I\x92\x98#\xec3&\x80\x01H\xa2(\x1as\xceG\xb6c\x97\xcc\x99\xb9\x8c1\xb3\xe2\x98\x91R\xcb\x12(\x9dN\xa7\xa3\xc9\x9c\x928AbY\xba\xcc;m\x03\xe7\xd2\xaf\x82\xdf\x9b\xcd\x9bq$<\xc94D\xa8>\x02\x91\xb3\x8f\xf4\x8e\xde\xdb\xddC\xa5RA\x14\x84p\xab5\x91\xccrR\xfe\x1e\x13\xa8\xaaz\xf1\xcc. uNq,\x18=\xc7\xb2\xa7puu\x15KK\xcb:\xf5\xab\xb8\xfeDN\x82\x82\xd3\xd9AQd\x8a\xdcQ\x7f\xef<\x1f\xc7P\x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x90$4e\x19\x1e\x8f\x07\xaa\xaa\xe2\xda\xb5k\xf0\xfb\xfd\xf8\xe4/\x9f\xe0\xc4\xc99\x8b@\xd2\x95k\xd8\x11\xa5\xd7\x83\xaa\xb6P\xaf\xd7\x91/\xe4\xb1\xbd\xbd\x8d;w\xee`sssP*\x95Z\x8a\xa2\xd4$I\xda\x95$\xe9.1\xf8!9\xd2\x95\x18\xc3S\xe6\xee#\xb4-\xffO\x0e@\xff\x07\x9e8\x83H\xaa\x88a\x00Q\xe2\x08)\xbf\xdf\xff\xb3\xd3\xa7O\xbf\x1e\x8b\xc7_\x88F\x22S\x89D\x22>11!&\x93I$\x12\x09\xc4b1\x84B!\x84BA\xf8|~\x8c\x8d\x89\xe0y\xc1f\xd1\xe2\x05\x8b\x03p\xe5\xbb\x15\xe4\xf3y{\xfa\xa7\xd5\xb2\x8c\xb8\xb7\xb7\x07\x9f\xcf\x87\x8f?\xfe\x18o\xbc\xf1\x86\xa3&\x01\xd3D\x7f0@KkA\x91\x15T*\x15\x1c\x1c\x1c \x9b\xcd\x22\x9b\xcd\x22\x93\xc9\x98\x85BAU\x14\xa5\xd9R\xd5R]\x92\xf6\xda\xedv\x96\x004K\xe4\xae\x90=^f\x0c\xff\xd4\xc3\xfd\xb3\xea\x00\xf7s\x84q\x00A\x00\x11\x001RZ\x9e\x98\x9e\x9e>\x95L&O\x86\xc3\xe1\xe9H$2\x19\x8f\xc7\x93\xc9T2\x10\x0a\x86\x10\x0c\x06\x11\x89D\x10\x89F\xad\xc7\xa1\x10\xfcD\xd89\x10\x08@\xd34lmmagg\xc7\x9a\xc4!b\xcb\xd3\xd3\xd3x\xe7\x9d\xdf\xe1\xd4\xcf\x17\xec\x19}UQ!\x13\xad\xa0r\xa5\x82\xb2E\xbbF\x1d\xa0W\xadV\x15Y\x96%M\xd3\xaa\xadV\xab(\xcbr\x9e\x18\xbdB\xee*\xd9\xdf\x9b\xb0F\xb4\xdb\xae\x04\xcfxV\xde\xf4g\xedb\x1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e0zn\xb82\xf8\xe7\xca\xe8?\x15\x07p\xbf\x06\xee\x01\xce\xc1~\x8d\xff\x9eB\x15\x5c\xe1{T(\x7fn\x0d\xfeSt\x80\x87y]\xff\xeb\xeb5\x7f\xe0\xd7\x9e\xbb\xeb\xbf\xb4,r\xf5\xb3p\x0e\x96\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x01\x00\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x14\x00\x00\x00\x14\x08\x06\x00\x00\x00\x8d\x89\x1d\x0d\x00\x00\x00\x06bKGD\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xdf\x06\x03\x09\x19\x0b\xb1J\x15\x0b\x00\x00\x00\x19tEXtComment\x00Created with GIMPW\x81\x0e\x17\x00\x00\x00hIDAT8\xcbc` \x0c\xde300\xfc\x87\xe2\xf7\x0c\x14\x82\x00$\xc3`8\x80\x14\x03\xce300\xecg``(\xc0b\x10:.\x80\xaa=\x8f\xcf@\x98b\x034\xaf\xa2\xe3\xf7P50>\x1c\xb0\xe008\x9e\x81\x81A\x90\x80o\xfa\xb1\x092bq!9\x00n\x0e\x13\x03\x95\xc1\xa8\x81\xa3\x06\x8e\x1a8<\x0d\xbc@\x86\x19(z\x00\xb8\xd7$a\xfe\xe8\x88\xf1\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x00\xf4\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x14\x00\x00\x00\x14\x08\x06\x00\x00\x00\x8d\x89\x1d\x0d\x00\x00\x00\x06bKGD\x00\x00\x00\x00\x00\x00\xf9C\xbb\x7f\x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xdf\x08\x11\x0e\x126J\xb9\xb7!\x00\x00\x00\x1diTXtComment\x00\x00\x00\x00\x00Created with GIMPd.e\x07\x00\x00\x00XIDAT8\xcbc`\xa02`\x84\xd2\xff\xc9\xd1\xfc\xff?D\x1b###\xdc<&j\xbb\x90\x05\x9b\x8d\x04\xbd\x85p\x11\x86Ki\xebB\x5c. \xe4\x03d\xf5Tw\xe1\xa8\x814\x8aeb\xd3#\xfd\xd3!\xae\xf47\xf0aHj\x98\xd15\xa7\xb0\x10[\x8a\xe0(\xffh\x1f\x86T\x07\x00qy\x1c6\xec\x80\xc0\xa9\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x00\x9e<RCC>\x0a<qresource>\x0a<file>qr.png</file>\x0a<file>calc.png</file>\x0a<file>copy.png</file>\x0a<file>qt_resources.qrc</file>\x0a<file>yubioath.png</file>\x0a</qresource>\x0a</RCC>\x0a"
qt_resource_name = b"\x00\x08\x08&Zg\x00c\x00a\x00l\x00c\x00.\x00p\x00n\x00g\x00\x0c\x08\xbcw\xc7\x00y\x00u\x00b\x00i\x00o\x00a\x00t\x00h\x00.\x00p\x00n\x00g\x00\x08\x06|Z\x07\x00c\x00o\x00p\x00y\x00.\x00p\x00n\x00g\x00\x06\x07\x85WG\x00q\x00r\x00.\x00p\x00n\x00g\x00\x10\x08X\xa8#\x00q\x00t\x00_\x00r\x00e\x00s\x00o\x00u\x00r\x00c\x00e\x00s\x00.\x00q\x00r\x00c"
qt_resource_struct = b"\x00\x00\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x01\x00\x00\x004\x00\x00\x00\x00\x00\x01\x00\x00W:\x00\x00\x00J\x00\x00\x00\x00\x00\x01\x00\x00X>\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x5c\x00\x00\x00\x00\x00\x01\x00\x00Y6\x00\x00\x00\x16\x00\x00\x00\x00\x00\x01\x00\x00\x01r"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/qt_resources.py | qt_resources.py |
from ..core.ccid import ScardDevice
from smartcard import System
from smartcard.ReaderMonitoring import ReaderMonitor, ReaderObserver
from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.Exceptions import SmartcardException
from smartcard.pcsc.PCSCExceptions import EstablishContextException
from PySide import QtCore
import weakref
class _CcidReaderObserver(ReaderObserver):
def __init__(self, controller):
self._controller = weakref.ref(controller)
self._monitor = ReaderMonitor()
self._monitor.addObserver(self)
def update(self, observable, tup):
(added, removed) = tup
c = self._controller()
if c:
c._update(added, removed)
def delete(self):
self._monitor.deleteObservers()
class _CcidCardObserver(CardObserver):
def __init__(self, controller):
self._controller = weakref.ref(controller)
self._monitor = CardMonitor()
self._monitor.addObserver(self)
def update(self, observable, tup):
(added, removed) = tup
c = self._controller()
if c:
c._update([card.reader for card in added],
[r.reader for r in removed])
def delete(self):
self._monitor.deleteObservers()
class CardStatus:
NoCard, InUse, Present = range(3)
class CardWatcher(QtCore.QObject):
status_changed = QtCore.Signal(int)
def __init__(self, reader_name, callback, parent=None):
super(CardWatcher, self).__init__(parent)
self._status = CardStatus.NoCard
self._device = lambda: None
self.reader_name = reader_name
self._callback = callback or (lambda _: _)
self._reader = None
self._reader_observer = _CcidReaderObserver(self)
self._card_observer = _CcidCardObserver(self)
try:
self._update(System.readers(), [])
except EstablishContextException:
pass # No PC/SC context!
def _update(self, added, removed):
if self._reader in removed: # Device removed
self.reader = None
self._set_status(CardStatus.NoCard)
if self._reader is None:
for reader in added:
if self.reader_name in reader.name:
self.reader = reader
self._set_status(CardStatus.Present)
return
@property
def status(self):
return self._status
def _set_status(self, value):
if self._status != value:
self._status = value
self.status_changed.emit(value)
@property
def reader(self):
return self._reader
@reader.setter
def reader(self, value):
self._reader = value
self._callback(self, value)
def open(self):
dev = self._device()
if dev is not None:
return dev
if self._reader:
conn = self._reader.createConnection()
try:
conn.connect()
self._set_status(CardStatus.Present)
dev = ScardDevice(conn)
self._device = weakref.ref(dev)
return dev
except SmartcardException:
self._set_status(CardStatus.InUse)
def __del__(self):
self._reader_observer.delete()
self._card_observer.delete()
def observe_reader(reader_name='Yubikey', callback=None):
return CardWatcher(reader_name, callback) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/ccid.py | ccid.py |
organization = "Yubico"
domain = "yubico.com"
app_name = "Yubico Authenticator"
win_title_1 = "Yubico Authenticator (%s)"
about_1 = "About: %s"
copyright = "Copyright © Yubico"
libraries = "Library versions"
version_1 = "Version: %s"
wait = "Please wait..."
error = "Error"
menu_file = "&File"
menu_help = "&Help"
action_about = "&About"
action_add = "&Add..."
action_password = "Set/Change &password"
action_settings = "&Settings"
action_delete = "&Delete"
action_show = "&Show credentials"
action_close = "&Close Window"
action_quit = "&Quit"
password = "Password"
settings = "Settings"
advanced = "Advanced"
search = "Search"
pass_required = "Password required"
remember = "Remember password"
no_key = "Insert a YubiKey..."
key_busy = "YubiKey already in use!"
key_present = "YubiKey found. Reading..."
key_removed = "YubiKey removed"
key_removed_desc = "There was an error communicating with the device!"
ykstd_slots = "YubiKey standard slots"
enable_slot_1 = "Read from slot %d"
n_digits = "Number of digits"
enable_systray = "Show in system tray"
kill_scdaemon = "Kill scdaemon on show"
reader_name = "Card reader name"
no_creds = "No credentials available"
add_cred = "New credential"
cred_name = "Credential name"
cred_key = "Secret key (base32)"
cred_type = "Credential type"
cred_totp = "Time based (TOTP)"
cred_hotp = "Counter based (HOTP)"
algorithm = "Algorithm"
invalid_name = "Invalid name"
invalid_name_desc = "Name must be at least 3 characters"
invalid_key = "Invalid key"
invalid_key_desc = "Key must be base32 encoded"
set_pass = "Set password"
new_pass = "New password (blank for none)"
ver_pass = "Verify new password"
pass_mismatch = "Passwords do not match"
pass_mismatch_desc = "Please enter the same password twice"
touch_title = "Touch required"
touch_desc = "Touch your YubiKey now"
delete_title = "Confirm credential deletion"
delete_desc_1 = """<span>Are you sure you want to delete the credential?</span>
<br>
This action cannot be undone.
<br><br>
<b>Delete credential: %s</b>
"""
slot = "YubiKey slot"
slot_2 = "Slot %d (%s)"
free = "free"
in_use = "in use"
require_touch = "Require touch"
no_slot = "No slot chosen"
no_slot_desc = "Please choose a slot to write the credential to"
overwrite_slot = "Overwrite slot?"
overwrite_slot_desc_1 = "This will overwrite the credential currently " \
"stored in slot %d. This action cannot be undone."
overwrite_entry = "Overwrite entry?"
overwrite_entry_desc = "An entry with this username already exists.\n\nDo " \
"you wish to overwrite it? This action cannot be undone."
qr_scan = "Scan a QR code"
qr_scanning = "Scanning for QR code..."
qr_not_found = "QR code not found"
qr_not_found_desc = "No usable QR code detected. Make sure the QR code is " \
"fully visible on your primary screen and try again."
qr_not_supported = "Credential not supported"
qr_not_supported_desc = "This credential type is not supported for slot " \
"based usage."
qr_invalid_type = "Invalid OTP type"
qr_invalid_type_desc = "Only TOTP and HOTP types are supported."
qr_invalid_digits = "Invalid number of digits"
qr_invalid_digits_desc = "An OTP may only contain 6 or 8 digits."
qr_invalid_algo = "Unsupported algorithm"
qr_invalid_algo_desc = "SHA1 and SHA256 are the only supported OTP " \
"algorithms at this time."
tt_slot_enabled_1 = "Check to calculate TOTP codes using the YubiKey " \
"standard slot %d credential."
tt_num_digits = "The number of digits to show for the credential."
tt_systray = "When checked, display an icon in the systray, and leave the " \
"application running there when closed."
tt_kill_scdaemon = "Kills any running scdaemon process when the window is " \
"shown. This is useful when using this application together with GnuPG " \
"to avoid GnuPG locking the device."
tt_reader_name = "Changes the default smartcard reader name to look for. " \
"This can be used to target a specific YubiKey when multiple are used, " \
"or to target an NFC reader."
ccid_disabled = '<b>CCID (smart card capabilities) is disabled on the ' \
'inserted YubiKey.</b><br><br>Without CCID enabled, you will only be ' \
'able to store 2 credentials.<br><br>' \
'<a href="%s">Learn how to enable CCID</a><br>'
no_space = "No space available"
no_space_desc = "There is not enough space to add another " \
"credential on your device.\n\nTo create free space to add a " \
"new credential, delete those you no longer need." | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/messages.py | messages.py |
from yubioath.yubicommon import qt
from .add_cred import B32Validator
from .. import messages as m
from ..qrparse import parse_qr_codes
from ..qrdecode import decode_qr_data
from ...core.utils import parse_uri
from PySide import QtGui
from base64 import b32decode
class AddCredDialog(qt.Dialog):
def __init__(self, worker, otp_slots=(0, 0), url=None, parent=None):
super(AddCredDialog, self).__init__(parent)
self.setWindowTitle(m.add_cred)
self._worker = worker
self._slot_status = otp_slots
self._build_ui()
def _build_ui(self):
layout = QtGui.QFormLayout(self)
self._qr_btn = QtGui.QPushButton(QtGui.QIcon(':/qr.png'), m.qr_scan)
self._qr_btn.clicked.connect(self._scan_qr)
layout.addRow(self._qr_btn)
self._cred_key = QtGui.QLineEdit()
self._cred_key.setValidator(B32Validator())
layout.addRow(m.cred_key, self._cred_key)
layout.addRow(QtGui.QLabel(m.slot))
self._slot = QtGui.QButtonGroup(self)
slot1_status = m.in_use if self._slot_status[0] else m.free
self._slot_1 = QtGui.QRadioButton(m.slot_2 % (1, slot1_status))
self._slot_1.setProperty('value', 1)
self._slot.addButton(self._slot_1)
layout.addRow(self._slot_1)
slot2_status = m.in_use if self._slot_status[1] else m.free
self._slot_2 = QtGui.QRadioButton(m.slot_2 % (2, slot2_status))
self._slot_2.setProperty('value', 2)
self._slot.addButton(self._slot_2)
layout.addRow(self._slot_2)
self._touch = QtGui.QCheckBox(m.require_touch)
layout.addRow(self._touch)
self._n_digits = QtGui.QComboBox()
self._n_digits.addItems(['6', '8'])
layout.addRow(m.n_digits, self._n_digits)
btns = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
btns.accepted.connect(self._save)
btns.rejected.connect(self.reject)
layout.addRow(btns)
def _save(self):
if not self._cred_key.hasAcceptableInput():
QtGui.QMessageBox.warning(self, m.invalid_key, m.invalid_key_desc)
self._cred_key.selectAll()
elif not self._slot.checkedButton():
QtGui.QMessageBox.warning(self, m.no_slot, m.no_slot_desc)
elif self._slot_status[self.slot - 1] \
and QtGui.QMessageBox.Ok != QtGui.QMessageBox.warning(
self, m.overwrite_slot, m.overwrite_slot_desc_1 % self.slot,
QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel):
return
else:
self.accept()
def _do_scan_qr(self, qimage):
for qr in parse_qr_codes(qimage):
try:
data = decode_qr_data(qr)
if data.startswith('otpauth://'):
return parse_uri(data)
except:
pass
return None
def _scan_qr(self):
winId = QtGui.QApplication.desktop().winId()
qimage = QtGui.QPixmap.grabWindow(winId).toImage()
self._worker.post(m.qr_scanning, (self._do_scan_qr, qimage),
self._handle_qr)
def _handle_qr(self, parsed):
if parsed:
if parsed['type'] != 'totp':
QtGui.QMessageBox.warning(self, m.qr_not_supported,
m.qr_not_supported_desc)
else:
self._cred_key.setText(parsed['secret'])
n_digits = parsed.get('digits', '6')
self._n_digits.setCurrentIndex(0 if n_digits == '6' else 1)
else:
QtGui.QMessageBox.warning(
self, m.qr_not_found, m.qr_not_found_desc)
@property
def key(self):
unpadded = self._cred_key.text().upper()
return b32decode(unpadded + '=' * (-len(unpadded) % 8))
@property
def slot(self):
return self._slot.checkedButton().property('value')
@property
def touch(self):
return self._touch.isChecked()
@property
def n_digits(self):
return int(self._n_digits.currentText()) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/view/add_cred_legacy.py | add_cred_legacy.py |
from yubioath.yubicommon import qt
from .. import messages as m
from PySide import QtGui
INDENT = 16
class SettingsDialog(qt.Dialog):
def __init__(self, parent, settings):
super(SettingsDialog, self).__init__(parent)
self.settings = settings
self.setWindowTitle(m.settings)
self.accepted.connect(self._save)
self._build_ui()
self._reset()
def _build_ui(self):
layout = QtGui.QFormLayout(self)
layout.addRow(self.section(m.ykstd_slots))
# YubiKey slot 1
self._slot1_enabled = QtGui.QCheckBox(m.enable_slot_1 % 1)
self._slot1_enabled.setToolTip(m.tt_slot_enabled_1 % 1)
layout.addRow(self._slot1_enabled)
self._slot1_digits = QtGui.QComboBox()
self._slot1_digits.addItems(['6', '8'])
self._slot1_enabled.stateChanged.connect(self._slot1_digits.setEnabled)
self._slot1_digits.setEnabled(False)
self._slot1_digits.setToolTip(m.tt_num_digits)
layout.addRow(m.n_digits, self._slot1_digits)
layout.labelForField(self._slot1_digits).setIndent(INDENT)
# YubiKey slot 2
self._slot2_enabled = QtGui.QCheckBox(m.enable_slot_1 % 2)
self._slot2_enabled.setToolTip(m.tt_slot_enabled_1 % 2)
layout.addRow(self._slot2_enabled)
self._slot2_digits = QtGui.QComboBox()
self._slot2_digits.addItems(['6', '8'])
self._slot2_enabled.stateChanged.connect(self._slot2_digits.setEnabled)
self._slot2_digits.setEnabled(False)
self._slot2_digits.setToolTip(m.tt_num_digits)
layout.addRow(m.n_digits, self._slot2_digits)
layout.labelForField(self._slot2_digits).setIndent(INDENT)
layout.addRow(self.section(m.advanced))
# Systray
self._systray = QtGui.QCheckBox(m.enable_systray)
self._systray.setToolTip(m.tt_systray)
layout.addRow(self._systray)
# Kill scdaemon
self._kill_scdaemon = QtGui.QCheckBox(m.kill_scdaemon)
self._kill_scdaemon.setToolTip(m.tt_kill_scdaemon)
layout.addRow(self._kill_scdaemon)
# Reader name
self._reader_name = QtGui.QLineEdit()
self._reader_name.setToolTip(m.tt_reader_name)
layout.addRow(m.reader_name, self._reader_name)
btns = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
btns.accepted.connect(self.accept)
btns.rejected.connect(self.reject)
layout.addRow(btns)
def _reset(self):
slot1 = self.settings.get('slot1', 0)
self._slot1_digits.setCurrentIndex(1 if slot1 == 8 else 0)
self._slot1_enabled.setChecked(bool(slot1))
slot2 = self.settings.get('slot2', 0)
self._slot2_digits.setCurrentIndex(1 if slot2 == 8 else 0)
self._slot2_enabled.setChecked(bool(slot2))
self._systray.setChecked(self.settings.get('systray', False))
self._kill_scdaemon.setChecked(
self.settings.get('kill_scdaemon', False))
self._reader_name.setText(self.settings.get('reader', 'Yubikey'))
@property
def slot1(self):
return self._slot1_enabled.isChecked() \
and int(self._slot1_digits.currentText())
@property
def slot2(self):
return self._slot2_enabled.isChecked() \
and int(self._slot2_digits.currentText())
@property
def systray(self):
return self._systray.isChecked()
@property
def kill_scdaemon(self):
return self._kill_scdaemon.isChecked()
@property
def reader_name(self):
return self._reader_name.text()
def _save(self):
self.settings['slot1'] = self.slot1
self.settings['slot2'] = self.slot2
self.settings['systray'] = self.systray
self.settings['kill_scdaemon'] = self.kill_scdaemon
self.settings['reader'] = self.reader_name | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/view/settings.py | settings.py |
from PySide import QtGui, QtCore
from .. import messages as m
from ...core.standard import TYPE_HOTP
from yubioath.yubicommon.qt.utils import connect_once
from time import time
TIMELEFT_STYLE = """
QProgressBar {
padding: 1px;
}
QProgressBar::chunk {
background-color: #2196f3;
margin: 0px;
width: 1px;
}
"""
class TimeleftBar(QtGui.QProgressBar):
expired = QtCore.Signal()
def __init__(self):
super(TimeleftBar, self).__init__()
self.setStyleSheet(TIMELEFT_STYLE)
self.setMaximumHeight(8)
self.setInvertedAppearance(True)
self.setRange(0, 30000)
self.setValue(0)
self.setTextVisible(False)
self._timer = 0
self._timeleft = 0
def set_timeleft(self, millis):
self._timeleft = max(0, millis)
self.setValue(min(millis, self.maximum()))
if self._timer == 0 and millis > 0:
self._timer = self.startTimer(250)
elif self._timer != 0 and millis <= 0:
self.killTimer(self._timer)
self._timer = 0
def timerEvent(self, event):
self.set_timeleft(max(0, self._timeleft - 250))
if self._timeleft == 0:
self.expired.emit()
class SearchBox(QtGui.QWidget):
def __init__(self, codes):
super(SearchBox, self).__init__()
self._codeswidget = codes
layout = QtGui.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._model = QtGui.QStringListModel()
self._completer = QtGui.QCompleter()
self._completer.setModel(self._model)
self._completer.setCompletionMode(QtGui.QCompleter.InlineCompletion)
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._lineedit = QtGui.QLineEdit()
self._lineedit.setPlaceholderText(m.search)
self._lineedit.setCompleter(self._completer)
self._lineedit.textChanged.connect(self._text_changed)
layout.addWidget(self._lineedit)
self._shortcut_focus = QtGui.QShortcut(
QtGui.QKeySequence.Find,
self._lineedit, self._set_focus)
self._shortcut_clear = QtGui.QShortcut(
QtGui.QKeySequence(self.tr("Esc")),
self._lineedit, self._lineedit.clear)
self._timer = QtCore.QTimer()
self._timer.setSingleShot(True)
self._timer.setInterval(300)
self._timer.timeout.connect(self._filter_changed)
def _set_focus(self):
self._lineedit.setFocus()
self._lineedit.selectAll()
def _text_changed(self, query):
self._timer.stop()
self._timer.start()
def _filter_changed(self):
search_filter = self._lineedit.text()
self._codeswidget.set_search_filter(search_filter)
def set_string_list(self, strings):
self._model.setStringList(strings)
class CodeMenu(QtGui.QMenu):
def __init__(self, parent):
super(CodeMenu, self).__init__(parent)
self.entry = parent.entry
self.addAction(m.action_delete).triggered.connect(self._delete)
def _delete(self):
res = QtGui.QMessageBox.warning(self, m.delete_title,
m.delete_desc_1 % self.entry.cred.name,
QtGui.QMessageBox.Ok,
QtGui.QMessageBox.Cancel)
if res == QtGui.QMessageBox.Ok:
self.entry.delete()
class Code(QtGui.QWidget):
def __init__(self, entry, timer, on_change):
super(Code, self).__init__()
self.entry = entry
self.issuer, self.name = self._split_issuer_name()
self._on_change = on_change
self.entry.changed.connect(self._draw)
self.timer = timer
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self._menu)
self._build_ui()
def _build_ui(self):
layout = QtGui.QHBoxLayout(self)
labels = QtGui.QVBoxLayout()
if self.issuer:
self._issuer_lbl = QtGui.QLabel(self.issuer)
labels.addWidget(self._issuer_lbl)
self._code_lbl = QtGui.QLabel()
labels.addWidget(self._code_lbl)
self._name_lbl = QtGui.QLabel(self.name)
labels.addWidget(self._name_lbl)
layout.addLayout(labels)
layout.addStretch()
self._calc_btn = QtGui.QPushButton(QtGui.QIcon(':/calc.png'), None)
self._calc_btn.clicked.connect(self._calc)
layout.addWidget(self._calc_btn)
self._calc_btn.setVisible(self.entry.manual)
self._copy_btn = QtGui.QPushButton(QtGui.QIcon(':/copy.png'), None)
self._copy_btn.clicked.connect(self._copy)
layout.addWidget(self._copy_btn)
self.timer.time_changed.connect(self._draw)
self._draw()
@property
def expired(self):
code = self.entry.code
return code.timestamp + code.ttl <= self.timer.time
def _draw(self):
if self.expired:
name_fmt = '<h2 style="color: gray;">%s</h2>'
else:
name_fmt = '<h2>%s</h2>'
code = self.entry.code
if self.entry.manual and self.entry.cred.oath_type != TYPE_HOTP:
self._calc_btn.setEnabled(self.expired)
self._code_lbl.setText(name_fmt % (code.code))
self._copy_btn.setEnabled(bool(code.code))
self._on_change()
def _copy(self):
QtCore.QCoreApplication.instance().clipboard().setText(
self.entry.code.code)
def _calc(self):
if self.entry.manual:
self._calc_btn.setDisabled(True)
self.entry.calculate()
if self.entry.cred.oath_type == TYPE_HOTP:
QtCore.QTimer.singleShot(
5000, lambda: self._calc_btn.setEnabled(True))
def _menu(self, pos):
CodeMenu(self).popup(self.mapToGlobal(pos))
def _split_issuer_name(self):
parts = self.entry.cred.name.split(':', 1)
if len(parts) == 2:
return parts
return None, self.entry.cred.name
def mouseDoubleClickEvent(self, event):
if event.button() is QtCore.Qt.LeftButton:
if (not self.entry.code.code or self.expired) and \
self.entry.manual:
def copy_close():
self._copy()
self.window().close()
connect_once(self.entry.changed, copy_close)
self.entry.calculate()
else:
self._copy() # TODO: Type code out with keyboard?
self.window().close()
event.accept()
class CodesList(QtGui.QWidget):
def __init__(
self, timer, credentials=[], on_change=None, search_filter=None):
super(CodesList, self).__init__()
self._codes = []
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
for cred in credentials:
if search_filter is not None and \
search_filter.lower() not in cred.cred.name.lower():
continue
code = Code(cred, timer, on_change)
layout.addWidget(code)
self._codes.append(code)
line = QtGui.QFrame()
line.setFrameShape(QtGui.QFrame.HLine)
line.setFrameShadow(QtGui.QFrame.Sunken)
layout.addWidget(line)
if not credentials:
no_creds = QtGui.QLabel(m.no_creds)
no_creds.setAlignment(QtCore.Qt.AlignCenter)
layout.addStretch()
layout.addWidget(no_creds)
layout.addStretch()
layout.addStretch()
def __del__(self):
for code in self._codes:
del code.entry
del code
class CodesWidget(QtGui.QWidget):
def __init__(self, controller):
super(CodesWidget, self).__init__()
self._controller = controller
controller.refreshed.connect(self.refresh)
controller.timer.time_changed.connect(self.refresh_timer)
self._filter = None
self._build_ui()
self.refresh()
self.refresh_timer()
def _build_ui(self):
layout = QtGui.QVBoxLayout(self)
self._timeleft = TimeleftBar()
layout.addWidget(self._timeleft)
self._scroll_area = QtGui.QScrollArea()
self._scroll_area.setWidgetResizable(True)
self._scroll_area.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOff)
self._scroll_area.setVerticalScrollBarPolicy(
QtCore.Qt.ScrollBarAsNeeded)
self._scroll_area.setWidget(QtGui.QWidget())
layout.addWidget(self._scroll_area)
self._searchbox = SearchBox(self)
layout.addWidget(self._searchbox)
def refresh_timer(self, timestamp=None):
if timestamp is None:
timestamp = self._controller.timer.time
if self._controller.has_expiring(timestamp):
self._timeleft.set_timeleft(1000 * (timestamp + 30 - time()))
else:
self._timeleft.set_timeleft(0)
def rebuild_completions(self):
creds = self._controller.credentials
stringlist = set()
if not creds:
return
for cred in creds:
cred_name = cred.cred.name
stringlist |= set(cred_name.split(':', 1))
self._searchbox.set_string_list(list(stringlist))
def set_search_filter(self, search_filter):
if len(search_filter) < 1:
search_filter = None
self._filter = search_filter
self.refresh()
def refresh(self):
self._scroll_area.takeWidget().deleteLater()
creds = self._controller.credentials
self.rebuild_completions()
self._scroll_area.setWidget(
CodesList(
self._controller.timer,
creds or [],
self.refresh_timer,
self._filter))
w = self._scroll_area.widget().minimumSizeHint().width()
w += self._scroll_area.verticalScrollBar().width()
self._scroll_area.setMinimumWidth(w) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/view/codes.py | codes.py |
from yubioath.yubicommon import qt
from ...core.standard import ALG_SHA1, ALG_SHA256, TYPE_TOTP, TYPE_HOTP
from ...core.utils import parse_uri
from .. import messages as m
from ..qrparse import parse_qr_codes
from ..qrdecode import decode_qr_data
from PySide import QtGui, QtCore
from base64 import b32decode
import re
NAME_VALIDATOR = QtGui.QRegExpValidator(QtCore.QRegExp(r'.{3,}'))
class B32Validator(QtGui.QValidator):
def __init__(self, parent=None):
super(B32Validator, self).__init__(parent)
self.partial = re.compile(r'^[ a-z2-7]+$', re.IGNORECASE)
def fixup(self, value):
unpadded = value.upper().rstrip('=').replace(' ', '')
return b32decode(unpadded + '=' * (-len(unpadded) % 8))
def validate(self, value, pos):
try:
self.fixup(value)
return QtGui.QValidator.Acceptable
except:
if self.partial.match(value):
return QtGui.QValidator.Intermediate
return QtGui.QValidator.Invalid
class AddCredDialog(qt.Dialog):
def __init__(self, worker, version, existing_entry_names, parent=None):
super(AddCredDialog, self).__init__(parent)
self._worker = worker
self._version = version
self.setWindowTitle(m.add_cred)
self._existing_entry_names = existing_entry_names
self._build_ui()
def _build_ui(self):
layout = QtGui.QFormLayout(self)
self._qr_btn = QtGui.QPushButton(QtGui.QIcon(':/qr.png'), m.qr_scan)
self._qr_btn.clicked.connect(self._scan_qr)
layout.addRow(self._qr_btn)
self._cred_name = QtGui.QLineEdit()
self._cred_name.setValidator(NAME_VALIDATOR)
layout.addRow(m.cred_name, self._cred_name)
self._cred_key = QtGui.QLineEdit()
self._cred_key.setValidator(B32Validator())
layout.addRow(m.cred_key, self._cred_key)
layout.addRow(QtGui.QLabel(m.cred_type))
self._cred_type = QtGui.QButtonGroup(self)
self._cred_totp = QtGui.QRadioButton(m.cred_totp)
self._cred_totp.setProperty('value', TYPE_TOTP)
self._cred_type.addButton(self._cred_totp)
layout.addRow(self._cred_totp)
self._cred_hotp = QtGui.QRadioButton(m.cred_hotp)
self._cred_hotp.setProperty('value', TYPE_HOTP)
self._cred_type.addButton(self._cred_hotp)
layout.addRow(self._cred_hotp)
self._cred_totp.setChecked(True)
self._n_digits = QtGui.QComboBox()
self._n_digits.addItems(['6', '8'])
layout.addRow(m.n_digits, self._n_digits)
self._algorithm = QtGui.QComboBox()
self._algorithm.addItems(['SHA-1', 'SHA-256'])
layout.addRow(m.algorithm, self._algorithm)
self._require_touch = QtGui.QCheckBox(m.require_touch)
# Touch-required support not available before 4.2.6
if self._version >= (4, 2, 6):
layout.addRow(self._require_touch)
btns = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok |
QtGui.QDialogButtonBox.Cancel)
btns.accepted.connect(self._save)
btns.rejected.connect(self.reject)
layout.addRow(btns)
def _do_scan_qr(self, qimage):
for qr in parse_qr_codes(qimage):
try:
data = decode_qr_data(qr)
if data.startswith('otpauth://'):
return parse_uri(data)
except:
pass
return None
def _scan_qr(self):
winId = QtGui.QApplication.desktop().winId()
qimage = QtGui.QPixmap.grabWindow(winId).toImage()
self._worker.post(m.qr_scanning, (self._do_scan_qr, qimage),
self._handle_qr)
def _handle_qr(self, parsed):
if parsed:
otp_type = parsed['type'].lower()
n_digits = parsed.get('digits', '6')
algo = parsed.get('algorithm', 'SHA1').upper()
if otp_type not in ['totp', 'hotp']:
QtGui.QMessageBox.warning(
self,
m.qr_invalid_type,
m.qr_invalid_type_desc)
return
if n_digits not in ['6', '8']:
QtGui.QMessageBox.warning(
self,
m.qr_invalid_digits,
m.qr_invalid_digits_desc)
return
if algo not in ['SHA1', 'SHA256']:
# RFC6238 says SHA512 is also supported,
# but it's not implemented here yet.
QtGui.QMessageBox.warning(
self,
m.qr_invalid_algo,
m.qr_invalid_algo_desc)
return
self._cred_name.setText(parsed['name'])
self._cred_key.setText(parsed['secret'])
self._n_digits.setCurrentIndex(0 if n_digits == '6' else 1)
self._algorithm.setCurrentIndex(0 if algo == 'SHA1' else 1)
if otp_type == 'totp':
self._cred_totp.setChecked(True)
else:
self._cred_hotp.setChecked(True)
else:
QtGui.QMessageBox.warning(
self,
m.qr_not_found,
m.qr_not_found_desc)
def _entry_exists(self):
return self._cred_name.text() in self._existing_entry_names
def _confirm_overwrite(self):
return QtGui.QMessageBox.question(
self, m.overwrite_entry, m.overwrite_entry_desc,
QtGui.QMessageBox.Yes | QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes
def _save(self):
if not self._cred_name.hasAcceptableInput():
QtGui.QMessageBox.warning(
self, m.invalid_name, m.invalid_name_desc)
self._cred_name.selectAll()
elif not self._cred_key.hasAcceptableInput():
QtGui.QMessageBox.warning(self, m.invalid_key, m.invalid_key_desc)
self._cred_key.selectAll()
elif self._entry_exists() and not self._confirm_overwrite():
self._cred_key.selectAll()
else:
self.accept()
@property
def name(self):
return self._cred_name.text()
@property
def key(self):
return self._cred_key.validator().fixup(self._cred_key.text())
@property
def oath_type(self):
return self._cred_type.checkedButton().property('value')
@property
def n_digits(self):
return int(self._n_digits.currentText())
@property
def algorithm(self):
return ALG_SHA1 if self._algorithm.currentIndex() == 0 else ALG_SHA256
@property
def require_touch(self):
return self._require_touch.isChecked() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/gui/view/add_cred.py | add_cred.py |
from __future__ import absolute_import
from PySide import QtCore
from collections import MutableMapping
__all__ = ['Settings', 'PySettings', 'convert_to']
def convert_to(value, target_type):
if target_type is list:
return [] if value is None else [value]
if target_type is int:
return 0 if value in ['', 'false', 'False'] else int(value)
if target_type is float:
return float(value)
if target_type is bool:
return value not in ['', 'false', 'False']
return value
class SettingsGroup(object):
def __init__(self, settings, mutex, group):
self._settings = settings
self._mutex = mutex
self._group = group
def __getattr__(self, method_name):
if hasattr(self._settings, method_name):
fn = getattr(self._settings, method_name)
def wrapped(*args, **kwargs):
try:
self._mutex.lock()
self._settings.beginGroup(self._group)
return fn(*args, **kwargs)
finally:
self._settings.endGroup()
self._mutex.unlock()
return wrapped
def rename(self, new_name):
data = dict((key, self.value(key)) for key in self.childKeys())
self.remove('')
self._group = new_name
for k, v in data.items():
self.setValue(k, v)
def __repr__(self):
return 'Group(%s)' % self._group
class Settings(QtCore.QObject):
def __init__(self, q_settings, wrap=True):
super(Settings, self).__init__()
self._mutex = QtCore.QMutex(QtCore.QMutex.Recursive)
self._wrap = wrap
self._q_settings = q_settings
def get_group(self, group):
g = SettingsGroup(self._q_settings, self._mutex, group)
if self._wrap:
g = PySettings(g)
return g
@staticmethod
def wrap(*args, **kwargs):
return Settings(QtCore.QSettings(*args, **kwargs))
class PySettings(MutableMapping):
def __init__(self, settings):
self._settings = settings
def __getattr__(self, method_name):
return getattr(self._settings, method_name)
def get(self, key, default=None):
val = self._settings.value(key, default)
if not isinstance(val, type(default)):
val = convert_to(val, type(default))
return val
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
self._settings.setValue(key, value)
def __delitem__(self, key):
self._settings.remove(key)
def __iter__(self):
for key in list(self.keys()):
yield key
def __len__(self):
return len(self._settings.childKeys())
def __contains__(self, key):
return self._settings.contains(key)
def keys(self):
return self._settings.childKeys()
def update(self, data):
for key, value in list(data.items()):
self[key] = value
def clear(self):
self._settings.remove('')
def __repr__(self):
return 'PySettings(%s)' % self._settings | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/qt/settings.py | settings.py |
from __future__ import absolute_import
from PySide import QtGui, QtCore
from .worker import Worker
import os
import sys
import importlib
from .. import compat
__all__ = ['Application', 'Dialog', 'MutexLocker']
TOP_SECTION = '<b>%s</b>'
SECTION = '<br><b>%s</b>'
class Dialog(QtGui.QDialog):
def __init__(self, *args, **kwargs):
super(Dialog, self).__init__(*args, **kwargs)
self.setWindowFlags(self.windowFlags() ^
QtCore.Qt.WindowContextHelpButtonHint)
self._headers = _Headers()
@property
def headers(self):
return self._headers
def section(self, title):
return self._headers.section(title)
class _Headers(object):
def __init__(self):
self._first = True
def section(self, title):
if self._first:
self._first = False
section = TOP_SECTION % title
else:
section = SECTION % title
return QtGui.QLabel(section)
class _MainWindow(QtGui.QMainWindow):
def __init__(self):
super(_MainWindow, self).__init__()
self._widget = None
def hide(self):
if sys.platform == 'darwin':
from .osx import app_services
app_services.osx_hide()
super(_MainWindow, self).hide()
def customEvent(self, event):
event.callback()
event.accept()
class Application(QtGui.QApplication):
_quit = False
def __init__(self, m=None, version=None):
super(Application, self).__init__(sys.argv)
self._determine_basedir()
self._read_package_version(version)
self.window = _MainWindow()
if m: # Run all strings through Qt translation
for key in dir(m):
if (isinstance(key, compat.string_types) and
not key.startswith('_')):
setattr(m, key, self.tr(getattr(m, key)))
self.worker = Worker(self.window, m)
def event(self, event):
if sys.platform == "darwin" and event.type() \
== QtCore.QEvent.ApplicationActivate:
self.window.show()
return super(Application, self).event(event)
def _determine_basedir(self):
if getattr(sys, 'frozen', False):
# we are running in a PyInstaller bundle
self.basedir = sys._MEIPASS
else:
# we are running in a normal Python environment
top_module_str = __package__.split('.')[0]
top_module = importlib.import_module(top_module_str)
self.basedir = os.path.dirname(top_module.__file__)
def _read_package_version(self, version):
if version is None:
return
pversion_fn = os.path.join(self.basedir, 'package_version.txt')
try:
with open(pversion_fn, 'r') as f:
pversion = int(f.read().strip())
except:
pversion = 0
if pversion > 0:
version += '.%d' % pversion
self.version = version
def ensure_singleton(self, name=None):
if not name:
name = self.applicationName()
from PySide import QtNetwork
self._l_socket = QtNetwork.QLocalSocket()
self._l_socket.connectToServer(name, QtCore.QIODevice.WriteOnly)
if self._l_socket.waitForConnected():
self._stop()
sys.exit(0)
else:
self._l_server = QtNetwork.QLocalServer()
if not self._l_server.listen(name):
QtNetwork.QLocalServer.removeServer(name)
self._l_server.listen(name)
self._l_server.newConnection.connect(self._show_window)
def _show_window(self):
self.window.show()
self.window.activateWindow()
def quit(self):
super(Application, self).quit()
self._quit = True
def _stop(self):
worker_thread = self.worker.thread()
worker_thread.quit()
worker_thread.wait()
self.deleteLater()
sys.stdout.flush()
sys.stderr.flush()
def exec_(self):
if not self._quit:
status = super(Application, self).exec_()
else:
status = 0
self._stop()
return status
class MutexLocker(object):
"""Drop-in replacement for QMutexLocker that can start unlocked."""
def __init__(self, mutex, lock=True):
self._mutex = mutex
self._locked = False
if lock:
self.relock()
def lock(self, try_lock=False):
if try_lock:
self._locked = self._mutex.tryLock()
else:
self._mutex.lock()
self._locked = True
return self._locked and self or None
def relock(self):
self.lock()
def unlock(self):
if self._locked:
self._mutex.unlock()
def __del__(self):
self.unlock() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/qt/classes.py | classes.py |
from __future__ import absolute_import
from PySide import QtCore, QtGui
from functools import wraps
from inspect import getargspec
__all__ = ['get_text', 'get_active_window', 'is_minimized', 'connect_once']
class _DefaultMessages(object):
def __init__(self, default_m, m=None):
self._defaults = default_m
self._m = m
def __getattr__(self, method_name):
if hasattr(self._m, method_name):
return getattr(self._m, method_name)
else:
return getattr(self._defaults, method_name)
def default_messages(_m, name='m'):
def inner(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
index = getargspec(fn).args.index(name)
if len(args) > index:
args = list(args)
args[index] = _DefaultMessages(_m, args[index])
else:
kwargs[name] = _DefaultMessages(_m, kwargs.get(name))
return fn(*args, **kwargs)
return wrapper
return inner
def get_text(*args, **kwargs):
flags = (
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowSystemMenuHint
)
kwargs['flags'] = flags
return QtGui.QInputDialog.getText(*args, **kwargs)
def get_active_window():
active_win = QtGui.QApplication.activeWindow()
if active_win is not None:
return active_win
wins = [w for w in QtGui.QApplication.topLevelWidgets()
if isinstance(w, QtGui.QDialog) and w.isVisible()]
if not wins:
return QtCore.QCoreApplication.instance().window
return wins[0] # TODO: If more than one candidates remain, find best one.
def connect_once(signal, slot):
_SignalConnector(signal, slot)
def is_minimized(window):
"""Returns True iff the window is minimized or has been sent to the tray"""
return not window.isVisible() or window.isMinimized()
class _SignalConnector(QtCore.QObject):
_instances = set()
def __init__(self, signal, slot):
super(_SignalConnector, self).__init__()
self.signal = signal
self.slot = slot
self._instances.add(self)
self.signal.connect(self.wrappedSlot)
def wrappedSlot(self, *args, **kwargs):
self._instances.discard(self)
self.signal.disconnect(self.wrappedSlot)
self.slot(*args, **kwargs) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/qt/utils.py | utils.py |
from __future__ import absolute_import
from PySide import QtGui, QtCore
from functools import partial
from os import getenv
from .utils import connect_once, get_active_window, default_messages
import traceback
class _Messages(object):
wait = 'Please wait...'
class _Event(QtCore.QEvent):
EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType())
def __init__(self, callback):
super(_Event, self).__init__(_Event.EVENT_TYPE)
self._callback = callback
def callback(self):
self._callback()
del self._callback
class Worker(QtCore.QObject):
_work_signal = QtCore.Signal(tuple)
_work_done_0 = QtCore.Signal()
@default_messages(_Messages)
def __init__(self, window, m):
super(Worker, self).__init__()
self.m = m
self.window = window
self._work_signal.connect(self.work)
self.work_thread = QtCore.QThread()
self.moveToThread(self.work_thread)
self.work_thread.start()
def post(self, title, fn, callback=None, return_errors=False):
busy = QtGui.QProgressDialog(title, None, 0, 0, get_active_window())
busy.setWindowTitle(self.m.wait)
busy.setWindowModality(QtCore.Qt.WindowModal)
busy.setMinimumDuration(0)
busy.setWindowFlags(
busy.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)
busy.show()
connect_once(self._work_done_0, busy.close)
self.post_bg(fn, callback, return_errors)
def post_bg(self, fn, callback=None, return_errors=False):
if isinstance(fn, tuple):
fn = partial(fn[0], *fn[1:])
self._work_signal.emit((fn, callback, return_errors))
def post_fg(self, fn):
if isinstance(fn, tuple):
fn = partial(fn[0], *fn[1:])
event = _Event(fn)
QtGui.QApplication.postEvent(self.window, event)
@QtCore.Slot(tuple)
def work(self, job):
QtCore.QThread.msleep(10) # Needed to yield
(fn, callback, return_errors) = job
try:
result = fn()
except Exception as e:
result = e
if getenv('DEBUG'):
traceback.print_exc()
if not return_errors:
def callback(e): raise e
if callback:
event = _Event(partial(callback, result))
QtGui.QApplication.postEvent(self.window, event)
self._work_done_0.emit() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/qt/worker.py | worker.py |
# flake8: noqa
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import json
import errno
import pkg_resources
from glob import glob
VS_VERSION_INFO = """
VSVersionInfo(
ffi=FixedFileInfo(
# filevers and prodvers should be always a tuple with four
# items: (1, 2, 3, 4)
# Set not needed items to zero 0.
filevers=%(ver_tup)r,
prodvers=%(ver_tup)r,
# Contains a bitmask that specifies the valid bits 'flags'r
mask=0x0,
# Contains a bitmask that specifies the Boolean attributes
# of the file.
flags=0x0,
# The operating system for which this file was designed.
# 0x4 - NT and there is no need to change it.
OS=0x4,
# The general type of file.
# 0x1 - the file is an application.
fileType=0x1,
# The function of the file.
# 0x0 - the function is not defined for this fileType
subtype=0x0,
# Creation date and time stamp.
date=(0, 0)
),
kids=[
StringFileInfo(
[
StringTable(
u'040904E4',
[StringStruct(u'FileDescription', u'%(name)s'),
StringStruct(u'FileVersion', u'%(ver_str)s'),
StringStruct(u'InternalName', u'%(internal_name)s'),
StringStruct(u'LegalCopyright', u'Copyright © 2015 Yubico'),
StringStruct(u'OriginalFilename', u'%(exe_name)s'),
StringStruct(u'ProductName', u'%(name)s'),
StringStruct(u'ProductVersion', u'%(ver_str)s')])
]),
VarFileInfo([VarStruct(u'Translation', [1033, 1252])])
]
)"""
data = json.loads(os.environ['pyinstaller_data'])
try:
data = dict((k, v.encode('ascii') if getattr(v, 'encode', None) else v)
for k, v in data.items())
except NameError:
pass # Python 3, encode not needed.
dist = pkg_resources.get_distribution(data['name'])
DEBUG = bool(data['debug'])
NAME = data['long_name']
WIN = sys.platform in ['win32', 'cygwin']
OSX = sys.platform in ['darwin']
ver_str = dist.version
if data['package_version'] > 0:
ver_str += '.%d' % data['package_version']
file_ext = '.exe' if WIN else ''
if WIN:
icon_ext = 'ico'
elif OSX:
icon_ext = 'icns'
else:
icon_ext = 'png'
ICON = os.path.join('resources', '%s.%s' % (data['name'], icon_ext))
if not os.path.isfile(ICON):
ICON = None
# Generate scripts from entry_points.
merge = []
entry_map = dist.get_entry_map()
console_scripts = entry_map.get('console_scripts', {})
gui_scripts = entry_map.get('gui_scripts', {})
for ep in list(gui_scripts.values()) + list(console_scripts.values()):
script_path = os.path.join(os.getcwd(), ep.name + '-script.py')
with open(script_path, 'w') as fh:
fh.write("import %s\n" % ep.module_name)
fh.write("%s.%s()\n" % (ep.module_name, '.'.join(ep.attrs)))
merge.append(
(Analysis([script_path], [dist.location], None, None, None, None),
ep.name, ep.name + file_ext)
)
MERGE(*merge)
# Read version information on Windows.
VERSION = None
if WIN:
VERSION = 'build/file_version_info.txt'
global int_or_zero # Needed due to how this script is invoked
def int_or_zero(v):
try:
return int(v)
except ValueError:
return 0
ver_tup = tuple(int_or_zero(v) for v in ver_str.split('.'))
# Windows needs 4-tuple.
if len(ver_tup) < 4:
ver_tup += (0,) * (4-len(ver_tup))
elif len(ver_tup) > 4:
ver_tup = ver_tup[:4]
# Write version info.
with open(VERSION, 'w') as f:
f.write(VS_VERSION_INFO % {
'name': NAME,
'internal_name': data['name'],
'ver_tup': ver_tup,
'ver_str': ver_str,
'exe_name': data['name'] + file_ext
})
pyzs = [PYZ(m[0].pure) for m in merge]
exes = []
for (a, a_name, a_name_ext), pyz in zip(merge, pyzs):
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name=a_name_ext,
debug=DEBUG,
strip=None,
upx=True,
console=DEBUG or a_name in console_scripts,
append_pkg=not OSX,
version=VERSION,
icon=ICON)
exes.append(exe)
# Sign the executable
if WIN:
os.system("signtool.exe sign /fd SHA256 /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" %
(exe.name))
collect = []
for (a, _, a_name), exe in zip(merge, exes):
collect += [exe, a.binaries, a.zipfiles, a.datas]
# Data files
collect.append([(os.path.basename(fn), fn, 'DATA') for fn in data['data_files']])
# DLLs, dylibs and executables should go here.
collect.append([(fn[4:], fn, 'BINARY') for fn in glob('lib/*')])
coll = COLLECT(*collect, strip=None, upx=True, name=NAME)
# Write package version for app to display
pversion_fn = os.path.join('dist', NAME, 'package_version.txt')
with open(pversion_fn, 'w') as f:
f.write(str(data['package_version']))
# Create .app for OSX
if OSX:
app = BUNDLE(coll,
name="%s.app" % NAME,
version=ver_str,
icon=ICON)
qt_conf = 'dist/%s.app/Contents/Resources/qt.conf' % NAME
qt_conf_dir = os.path.dirname(qt_conf)
try:
os.makedirs(qt_conf_dir)
except OSError as e:
if not (e.errno == errno.EEXIST and os.path.isdir(qt_conf_dir)):
raise
with open(qt_conf, 'w') as f:
f.write('[Path]\nPlugins = plugins')
# Create Windows installer
if WIN:
installer_cfg = 'resources/win-installer.nsi'
if os.path.isfile(installer_cfg):
os.system('makensis.exe -D"VERSION=%s" %s' % (ver_str, installer_cfg))
installer = "dist/%s-%s-win.exe" % (data['name'], ver_str)
os.system("signtool.exe sign /fd SHA256 /t http://timestamp.verisign.com/scripts/timstamp.dll \"%s\"" %
(installer))
print("Installer created: %s" % installer) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/setup/pyinstaller_spec.py | pyinstaller_spec.py |
from __future__ import absolute_import
from setuptools import setup as _setup, find_packages, Command
from setuptools.command.sdist import sdist
from distutils import log
from distutils.errors import DistutilsSetupError
from datetime import date
from glob import glob
import os
import re
__dependencies__ = []
__all__ = ['get_version', 'setup', 'release']
VERSION_PATTERN = re.compile(r"(?m)^__version__\s*=\s*['\"](.+)['\"]$")
DEPENDENCY_PATTERN = re.compile(
r"(?m)__dependencies__\s*=\s*\[((['\"].+['\"]\s*(,\s*)?)+)\]")
YC_DEPENDENCY_PATTERN = re.compile(
r"(?m)__yc_dependencies__\s*=\s*\[((['\"].+['\"]\s*(,\s*)?)+)\]")
base_module = __name__.rsplit('.', 1)[0]
def get_version(module_name_or_file=None):
"""Return the current version as defined by the given module/file."""
if module_name_or_file is None:
parts = base_module.split('.')
module_name_or_file = parts[0] if len(parts) > 1 else \
find_packages(exclude=['test', 'test.*'])[0]
if os.path.isdir(module_name_or_file):
module_name_or_file = os.path.join(module_name_or_file, '__init__.py')
with open(module_name_or_file, 'r') as f:
match = VERSION_PATTERN.search(f.read())
return match.group(1)
def get_dependencies(module):
basedir = os.path.dirname(__file__)
fn = os.path.join(basedir, module + '.py')
if os.path.isfile(fn):
with open(fn, 'r') as f:
match = DEPENDENCY_PATTERN.search(f.read())
if match:
return [s.strip().strip('"\'')
for s in match.group(1).split(',')]
return []
def get_yc_dependencies(module):
basedir = os.path.dirname(__file__)
fn = os.path.join(basedir, module + '.py')
if os.path.isfile(fn):
with open(fn, 'r') as f:
match = YC_DEPENDENCY_PATTERN.search(f.read())
if match:
return [s.strip().strip('"\'')
for s in match.group(1).split(',')]
return []
def get_package(module):
return base_module + '.' + module
def setup(**kwargs):
# TODO: Find a better way to pass this to a command.
os.environ['setup_long_name'] = kwargs.pop('long_name', kwargs.get('name'))
if 'version' not in kwargs:
kwargs['version'] = get_version()
packages = kwargs.setdefault(
'packages',
find_packages(exclude=['test', 'test.*', base_module + '.*']))
packages.append(__name__)
install_requires = kwargs.setdefault('install_requires', [])
yc_blacklist = kwargs.pop('yc_requires_exclude', [])
yc_requires = kwargs.pop('yc_requires', [])
yc_requires_stack = yc_requires[:]
while yc_requires_stack:
yc_module = yc_requires_stack.pop()
for yc_dep in get_yc_dependencies(yc_module):
if yc_dep not in yc_requires:
yc_requires.append(yc_dep)
yc_requires_stack.append(yc_dep)
for yc_module in yc_requires:
packages.append(get_package(yc_module))
for dep in get_dependencies(yc_module):
if dep not in install_requires and dep not in yc_blacklist:
install_requires.append(dep)
cmdclass = kwargs.setdefault('cmdclass', {})
cmdclass.setdefault('release', release)
cmdclass.setdefault('build_man', build_man)
cmdclass.setdefault('sdist', custom_sdist)
return _setup(**kwargs)
class custom_sdist(sdist):
def run(self):
self.run_command('build_man')
# Run if available:
if 'qt_resources' in self.distribution.cmdclass:
self.run_command('qt_resources')
sdist.run(self)
class build_man(Command):
description = "create man pages from asciidoc source"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
self.cwd = os.getcwd()
self.fullname = self.distribution.get_fullname()
self.name = self.distribution.get_name()
self.version = self.distribution.get_version()
def run(self):
if os.getcwd() != self.cwd:
raise DistutilsSetupError("Must be in package root!")
for fname in glob(os.path.join('man', '*.adoc')):
self.announce("Converting: " + fname, log.INFO)
self.execute(os.system,
('a2x -d manpage -f manpage "%s"' % fname,))
class release(Command):
description = "create and release a new version"
user_options = [
('keyid', None, "GPG key to sign with"),
('skip-tests', None, "skip running the tests"),
('pypi', None, "publish to pypi"),
]
boolean_options = ['skip-tests', 'pypi']
def initialize_options(self):
self.keyid = None
self.skip_tests = 0
self.pypi = 0
def finalize_options(self):
self.cwd = os.getcwd()
self.fullname = self.distribution.get_fullname()
self.name = self.distribution.get_name()
self.version = self.distribution.get_version()
def _verify_version(self):
with open('NEWS', 'r') as news_file:
line = news_file.readline()
now = date.today().strftime('%Y-%m-%d')
if not re.search(r'Version %s \(released %s\)' % (self.version, now),
line):
raise DistutilsSetupError("Incorrect date/version in NEWS!")
def _verify_tag(self):
if os.system('git tag | grep -q "^%s\$"' % self.fullname) == 0:
raise DistutilsSetupError(
"Tag '%s' already exists!" % self.fullname)
def _verify_not_dirty(self):
if os.system('git diff --shortstat | grep -q "."') == 0:
raise DistutilsSetupError("Git has uncommitted changes!")
def _sign(self):
if os.path.isfile('dist/%s.tar.gz.asc' % self.fullname):
# Signature exists from upload, re-use it:
sign_opts = ['--output dist/%s.tar.gz.sig' % self.fullname,
'--dearmor dist/%s.tar.gz.asc' % self.fullname]
else:
# No signature, create it:
sign_opts = ['--detach-sign', 'dist/%s.tar.gz' % self.fullname]
if self.keyid:
sign_opts.insert(1, '--default-key ' + self.keyid)
self.execute(os.system, ('gpg ' + (' '.join(sign_opts)),))
if os.system('gpg --verify dist/%s.tar.gz.sig' % self.fullname) != 0:
raise DistutilsSetupError("Error verifying signature!")
def _tag(self):
tag_opts = ['-s', '-m ' + self.fullname, self.fullname]
if self.keyid:
tag_opts[0] = '-u ' + self.keyid
self.execute(os.system, ('git tag ' + (' '.join(tag_opts)),))
def run(self):
if os.getcwd() != self.cwd:
raise DistutilsSetupError("Must be in package root!")
self._verify_version()
self._verify_tag()
self._verify_not_dirty()
self.run_command('check')
self.execute(os.system, ('git2cl > ChangeLog',))
self.run_command('sdist')
if not self.skip_tests:
try:
self.run_command('test')
except SystemExit as e:
if e.code != 0:
raise DistutilsSetupError("There were test failures!")
if self.pypi:
cmd_obj = self.distribution.get_command_obj('upload')
cmd_obj.sign = True
if self.keyid:
cmd_obj.identity = self.keyid
self.run_command('upload')
self._sign()
self._tag()
self.announce("Release complete! Don't forget to:", log.INFO)
self.announce("")
self.announce(" git push && git push --tags", log.INFO)
self.announce("") | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/setup/__init__.py | __init__.py |
from __future__ import absolute_import
import os.path
import re
import sys
import glob
import platform
import ctypes
import ctypes.util
def _environ_path(name):
if name in os.environ:
return os.environ[name].split(":")
else:
return []
class LibraryLoader(object):
def __init__(self):
self.other_dirs = []
def load_library(self, libname, version=None):
"""Given the name of a library, load it."""
paths = self.getpaths(libname)
for path in paths:
if os.path.exists(path):
return self.load(path)
raise ImportError("%s not found." % libname)
def load(self, path):
"""Given a path to a library, load it."""
try:
# Darwin requires dlopen to be called with mode RTLD_GLOBAL instead
# of the default RTLD_LOCAL. Without this, you end up with
# libraries not being loadable, resulting in "Symbol not found"
# errors
if sys.platform == 'darwin':
return ctypes.CDLL(path, ctypes.RTLD_GLOBAL)
else:
return ctypes.cdll.LoadLibrary(path)
except OSError as e:
raise ImportError(e)
def getpaths(self, libname):
"""Return a list of paths where the library might be found."""
if os.path.isabs(libname):
yield libname
else:
# FIXME / TODO return '.' and os.path.dirname(__file__)
for path in self.getplatformpaths(libname):
yield path
path = ctypes.util.find_library(libname)
if path:
yield path
def getplatformpaths(self, libname):
return []
# Darwin (Mac OS X)
class DarwinLibraryLoader(LibraryLoader):
name_formats = ["lib%s.dylib", "lib%s.so", "lib%s.bundle", "%s.dylib",
"%s.so", "%s.bundle", "%s"]
def getplatformpaths(self, libname):
if os.path.pathsep in libname:
names = [libname]
else:
names = [format % libname for format in self.name_formats]
for dir in self.getdirs(libname):
for name in names:
yield os.path.join(dir, name)
def getdirs(self, libname):
'''Implements the dylib search as specified in Apple documentation:
http://developer.apple.com/documentation/DeveloperTools/Conceptual/
DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html
Before commencing the standard search, the method first checks
the bundle's ``Frameworks`` directory if the application is running
within a bundle (OS X .app).
'''
dyld_fallback_library_path = _environ_path(
"DYLD_FALLBACK_LIBRARY_PATH")
if not dyld_fallback_library_path:
dyld_fallback_library_path = [os.path.expanduser('~/lib'),
'/usr/local/lib', '/usr/lib']
dirs = []
if '/' in libname:
dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
else:
dirs.extend(_environ_path("LD_LIBRARY_PATH"))
dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
dirs.extend(self.other_dirs)
dirs.append(".")
dirs.append(os.path.dirname(__file__))
if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
dirs.append(os.path.join(
os.environ['RESOURCEPATH'],
'..',
'Frameworks'))
if hasattr(sys, 'frozen'):
dirs.append(sys._MEIPASS)
dirs.append(
os.path.join(os.path.dirname(sys.executable), '../Frameworks'))
dirs.extend(dyld_fallback_library_path)
return dirs
# Posix
class PosixLibraryLoader(LibraryLoader):
_ld_so_cache = None
def load_library(self, libname, version=None):
try:
return self.load(ctypes.util.find_library(libname))
except ImportError:
return super(PosixLibraryLoader, self).load_library(
libname, version)
def _create_ld_so_cache(self):
# Recreate search path followed by ld.so. This is going to be
# slow to build, and incorrect (ld.so uses ld.so.cache, which may
# not be up-to-date). Used only as fallback for distros without
# /sbin/ldconfig.
#
# We assume the DT_RPATH and DT_RUNPATH binary sections are omitted.
directories = []
for name in ("LD_LIBRARY_PATH",
"SHLIB_PATH", # HPUX
"LIBPATH", # OS/2, AIX
"LIBRARY_PATH", # BE/OS
):
if name in os.environ:
directories.extend(os.environ[name].split(os.pathsep))
directories.extend(self.other_dirs)
directories.append(".")
directories.append(os.path.dirname(__file__))
try:
directories.extend([dir.strip()
for dir in open('/etc/ld.so.conf')])
except IOError:
pass
unix_lib_dirs_list = ['/lib', '/usr/lib', '/lib64', '/usr/lib64']
if sys.platform.startswith('linux'):
# Try and support multiarch work in Ubuntu
# https://wiki.ubuntu.com/MultiarchSpec
bitage = platform.architecture()[0]
if bitage.startswith('32'):
# Assume Intel/AMD x86 compat
unix_lib_dirs_list += [
'/lib/i386-linux-gnu', '/usr/lib/i386-linux-gnu']
elif bitage.startswith('64'):
# Assume Intel/AMD x86 compat
unix_lib_dirs_list += [
'/lib/x86_64-linux-gnu', '/usr/lib/x86_64-linux-gnu']
else:
# guess...
unix_lib_dirs_list += glob.glob('/lib/*linux-gnu')
directories.extend(unix_lib_dirs_list)
cache = {}
lib_re = re.compile(r'lib(.*)\.s[ol]')
for dir in directories:
try:
for path in glob.glob("%s/*.s[ol]*" % dir):
file = os.path.basename(path)
# Index by filename
if file not in cache:
cache[file] = path
# Index by library name
match = lib_re.match(file)
if match:
library = match.group(1)
if library not in cache:
cache[library] = path
except OSError:
pass
self._ld_so_cache = cache
def getplatformpaths(self, libname):
if self._ld_so_cache is None:
self._create_ld_so_cache()
result = self._ld_so_cache.get(libname)
if result:
yield result
path = ctypes.util.find_library(libname)
if path:
yield os.path.join("/lib", path)
# Windows
class _WindowsLibrary(object):
def __init__(self, path):
self.cdll = ctypes.cdll.LoadLibrary(path)
self.windll = ctypes.windll.LoadLibrary(path)
def __getattr__(self, name):
try:
return getattr(self.cdll, name)
except AttributeError:
try:
return getattr(self.windll, name)
except AttributeError:
raise
class WindowsLibraryLoader(LibraryLoader):
name_formats = ["%s.dll", "lib%s.dll", "%slib.dll"]
def load_library(self, libname, version=None):
try:
result = LibraryLoader.load_library(self, libname, version)
except ImportError:
result = None
if os.path.sep not in libname:
formats = self.name_formats[:]
if version:
formats.append("lib%%s-%s.dll" % version)
for name in formats:
try:
result = getattr(ctypes.cdll, name % libname)
if result:
break
except WindowsError:
result = None
if result is None:
try:
result = getattr(ctypes.cdll, libname)
except WindowsError:
result = None
if result is None:
raise ImportError("%s not found." % libname)
return result
def load(self, path):
return _WindowsLibrary(path)
def getplatformpaths(self, libname):
if os.path.sep not in libname:
for name in self.name_formats:
dll_in_current_dir = os.path.abspath(name % libname)
if os.path.exists(dll_in_current_dir):
yield dll_in_current_dir
path = ctypes.util.find_library(name % libname)
if path:
yield path
# Platform switching
# If your value of sys.platform does not appear in this dict, please contact
# the Ctypesgen maintainers.
loaderclass = {
"darwin": DarwinLibraryLoader,
"cygwin": WindowsLibraryLoader,
"win32": WindowsLibraryLoader
}
loader = loaderclass.get(sys.platform, PosixLibraryLoader)()
def add_library_search_dirs(other_dirs):
loader.other_dirs = other_dirs
load_library = loader.load_library
del loaderclass | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/yubicommon/ctypes/libloader.py | libloader.py |
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# 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/>.
#
# Additional permission under GNU GPL version 3 section 7
#
# If you modify this program, or any covered work, by linking or
# combining it with the OpenSSL project's OpenSSL library (or a
# modified version of that library), containing parts covered by the
# terms of the OpenSSL or SSLeay licenses, We grant you additional
# permission to convey the resulting work. Corresponding Source for a
# non-source form of such a combination shall include the source code
# for the parts of OpenSSL used as well as that of the covered work.
from __future__ import print_function
from .. import __version__
from ..core.ccid import open_scard
from ..core.standard import ALG_SHA1, ALG_SHA256, TYPE_HOTP, TYPE_TOTP
from ..core.utils import parse_uri
from ..core.exc import NoSpaceError
from .keystore import get_keystore
from .controller import CliController
from time import time
from base64 import b32decode
import click
import sys
def print_creds(results):
if not results:
click.echo('No credentials found.')
return
longest = max(len(r[0].name) for r in results)
format_str = '{:<%d} {:>10}' % longest
for (cred, code) in results:
if code is None:
if cred.oath_type == TYPE_HOTP:
code = '[HOTP credential]'
elif cred.touch:
code = '[Touch credential]'
click.echo(format_str.format(cred.name, code))
CLICK_CONTEXT_SETTINGS = dict(
help_option_names=['-h', '--help']
)
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('yubioath {}'.format(__version__))
ctx.exit()
@click.group(context_settings=CLICK_CONTEXT_SETTINGS)
@click.option('-v', '--version', is_flag=True, callback=print_version,
expose_value=False, is_eager=True, help='Prints the version of '
'the application and exits.')
@click.option('-r', '--reader', default='YubiKey', help='Name to match '
'smartcard reader against (case insensitive).')
@click.option('-R', '--remember', is_flag=True, help='Remember any entered '
'access key for later use.')
@click.pass_context
def cli(ctx, reader, remember):
"""
Read OATH one time passwords from a YubiKey.
"""
ctx.obj['dev'] = open_scard(reader)
ctx.obj['controller'] = CliController(get_keystore(), remember)
ctx.obj['remember'] = remember
@cli.command()
@click.argument('query', nargs=-1, required=False)
@click.option('-s1', '--slot1', type=int, default=0)
@click.option('-s2', '--slot2', type=int, default=0)
@click.option('-t', '--timestamp', type=int, default=int(time()) + 5)
@click.pass_context
def show(ctx, query, slot1, slot2, timestamp):
"""
Print one or more codes from a YubiKey.
"""
dev = ctx.obj['dev']
controller = ctx.obj['controller']
creds = controller.read_creds(dev, slot1, slot2, timestamp)
if creds is None:
ctx.fail('No YubiKey found!')
if query:
query = ' '.join(query)
# Filter based on query. If exact match, show only that result.
matched = []
for cred, code in creds:
if cred.name == query:
matched = [(cred, code)]
break
if query.lower() in cred.name.lower():
matched.append((cred, code))
# Only calculate Touch/HOTP codes if the credential is singled out.
if len(matched) == 1:
(cred, code) = matched[0]
if not code:
if cred.touch:
controller._prompt_touch()
creds = [(cred, cred.calculate(timestamp))]
else:
creds = [(cred, code)]
else:
creds = matched
print_creds(creds)
@cli.command()
@click.argument('key')
@click.option('-S', '--destination', type=click.IntRange(0, 2), default=0)
@click.option('-N', '--name', required=False, help='Credential name.')
@click.option(
'-A', '--oath-type', type=click.Choice(['totp', 'hotp']), default='totp',
help='Specify whether this is a time or counter-based OATH credential.')
@click.option('-D', '--digits', type=click.Choice(['6', '8']), default='6',
callback=lambda c, p, v: int(v), help='Number of digits.')
@click.option(
'-H', '--hmac-algorithm', type=click.Choice(['SHA1', 'SHA256']),
default='SHA1', help='HMAC algorithm for OTP generation.')
@click.option(
'-I', '--imf', type=int, default=0, help='Initial moving factor.')
@click.option('-T', '--touch', is_flag=True, help='Require touch.')
@click.pass_context
def put(
ctx, key, destination, name, oath_type,
hmac_algorithm, digits, imf, touch):
"""
Stores a new OATH credential in the YubiKey.
"""
if key.startswith('otpauth://'):
parsed = parse_uri(key)
key = parsed['secret']
name = parsed.get('name')
oath_type = parsed.get('type')
hmac_algorithm = parsed.get('algorithm', 'SHA1').upper()
digits = int(parsed.get('digits', '6'))
imf = int(parsed.get('counter', '0'))
if oath_type not in ['totp', 'hotp']:
ctx.fail('Invalid OATH credential type')
if hmac_algorithm == 'SHA1':
algo = ALG_SHA1
elif hmac_algorithm == 'SHA256':
algo = ALG_SHA256
else:
ctx.fail('Invalid HMAC algorithm')
if digits == 5 and name.startswith('Steam:'):
# Steam is a special case where we allow the otpauth
# URI to contain a 'digits' value of '5'.
digits = 6
if digits not in [6, 8]:
ctx.fail('Invalid number of digits for OTP')
digits = digits or 6
unpadded = key.upper()
key = b32decode(unpadded + '=' * (-len(unpadded) % 8))
controller = ctx.obj['controller']
if destination == 0:
dev = ctx.obj['dev'] or ctx.fail('No YubiKey found!')
name = name or click.prompt('Enter a name for the credential')
oath_type = TYPE_TOTP if oath_type == 'totp' else TYPE_HOTP
try:
controller.add_cred(dev, name, key, oath_type, digits=digits,
imf=imf, algo=algo, require_touch=touch)
except NoSpaceError:
ctx.fail(
'There is not enough space to add another credential on your'
' device. To create free space to add a new '
'credential, delete those you no longer need.')
else:
controller.add_cred_legacy(destination, key, touch)
@cli.command()
@click.argument('name')
@click.pass_context
def delete(ctx, name):
"""
Deletes a credential from the YubiKey.
"""
controller = ctx.obj['controller']
if name in ['YubiKey slot 1', 'YubiKey slot 2']:
controller.delete_cred_legacy(int(name[-1]))
else:
dev = ctx.obj['dev'] or ctx.fail('No YubiKey found!')
controller.delete_cred(dev, name)
click.echo('Credential deleted!')
@cli.group()
def password():
"""
Manage the password used to protect access to the YubiKey.
"""
@password.command()
@click.password_option('-p', '--password')
@click.pass_context
def set(ctx, password):
"""
Set a new password.
"""
dev = ctx.obj['dev'] or ctx.fail('No YubiKey found!')
controller = ctx.obj['controller']
remember = ctx.obj['remember']
controller.set_password(dev, password, remember)
click.echo('New password set!')
@password.command()
@click.pass_context
def unset(ctx):
"""
Removes the need to enter a password to access credentials.
"""
dev = ctx.obj['dev'] or ctx.fail('No YubiKey found!')
controller = ctx.obj['controller']
controller.set_password(dev, '')
click.echo('Password cleared!')
@password.command()
@click.pass_context
def forget(ctx):
controller = ctx.obj['controller']
controller.keystore.clear()
@cli.command()
@click.option('-f', '--force', is_flag=True,
help='Confirm the action without prompting.')
@click.pass_context
def reset(ctx, force):
"""
Deletes all stored OATH credentials from non-slot based storage.
"""
dev = ctx.obj['dev'] or ctx.fail('No YubiKey found!')
controller = ctx.obj['controller']
force or click.confirm('WARNING!!! Really delete all non slot-based OATH '
'credentials from the YubiKey?', abort=True)
controller.reset_device(dev)
click.echo('The OATH functionality of your YubiKey has been reset.\n')
@cli.command(context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True
))
@click.option('-h', '--help', is_flag=True)
@click.pass_context
def gui(ctx, help):
"""
Launches the Yubico Authenticator graphical interface.
"""
try:
import PySide
assert PySide
except ImportError:
ctx.fail('GUI requires PySide to run.')
import yubioath.gui.__main__
sys.argv.remove(ctx.command.name)
sys.argv[0] = sys.argv[0] + ' ' + ctx.command.name
yubioath.gui.__main__.main()
def intersects(a, b):
return bool(set(a) & set(b))
def main():
commands = list(cli.commands) + CLICK_CONTEXT_SETTINGS['help_option_names']
buf = [sys.argv[0]]
rest = sys.argv[1:]
found_command = False
while rest:
first = rest.pop(0)
if first in commands:
found_command = True
break # We have a command, no more processing needed.
for p in cli.params:
if first in p.opts: # first is an option.
buf.append(first)
if not p.is_flag and rest: # Has a value.
buf.append(rest.pop(0))
break # Restart checking
else: # No match, put the argument back and stop.
rest.insert(0, first)
break
if not found_command: # No command found, default to "show".
sys.argv = buf + ['show'] + rest
try:
cli(obj={})
except KeyboardInterrupt:
sys.stderr.write('\nInterrupted, exiting.\n')
sys.exit(130)
if __name__ == '__main__':
main() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/cli/__main__.py | __main__.py |
from .standard import YubiOathCcid
from .legacy_ccid import LegacyOathCcid
from .exc import CardError, InvalidSlotError, NeedsTouchError
import time
import sys
try:
from .legacy_otp import open_otp, LegacyOathOtp, LegacyCredential
except ImportError:
sys.stderr.write('libykpers not found!\n')
open_otp = None
class Controller(object):
@property
def otp_supported(self):
return bool(open_otp)
def open_otp(self):
otp_dev = open_otp()
if otp_dev:
return LegacyOathOtp(otp_dev)
def _prompt_touch(self):
pass
def _end_prompt_touch(self):
pass
def unlock(self, std):
raise ValueError('Password required')
def read_slot_ccid(self, std, slot, digits, timestamp=None):
cred = LegacyCredential(std, slot, digits)
try:
return (cred, cred.calculate(timestamp))
except InvalidSlotError:
return (cred, 'INVALID')
def read_slot_otp(self, cred, timestamp=None, use_touch=False):
if cred.touch:
if not use_touch:
raise NeedsTouchError()
self._prompt_touch()
try:
return (cred, cred.calculate(timestamp))
except InvalidSlotError:
return (cred, 'INVALID')
except NeedsTouchError:
if use_touch:
try:
time.sleep(0.1) # Give the key a little time...
self._prompt_touch()
start = time.time()
return (cred, cred.calculate(timestamp))
except InvalidSlotError:
error = 'INVALID' if time.time() - start < 1 else 'TIMEOUT'
return (cred, error)
return (cred, None)
finally:
if cred.touch:
self._end_prompt_touch()
def read_creds(self, ccid_dev, slot1, slot2, timestamp, mayblock=True):
results = []
key_found = False
do_legacy = mayblock and bool(slot1 or slot2)
legacy_creds = [None, None]
if ccid_dev:
try:
std = YubiOathCcid(ccid_dev)
key_found = True
if std.locked:
self.unlock(std)
results.extend(std.calculate_all(timestamp))
except CardError:
pass # No applet?
if do_legacy:
try:
legacy = LegacyOathCcid(ccid_dev)
for (slot, digits) in [(0, slot1), (1, slot2)]:
if digits:
try:
legacy_creds[slot] = self.read_slot_ccid(
legacy, slot+1, digits, timestamp)
except NeedsTouchError:
pass # Handled over OTP instead
except CardError:
pass # No applet?
if self.otp_supported and ((slot1 and not legacy_creds[0])
or (slot2 and not legacy_creds[1])):
if ccid_dev:
ccid_dev.close()
legacy = self.open_otp()
if legacy:
key_found = True
if not legacy_creds[0] and slot1:
legacy_creds[0] = self.read_slot_otp(
LegacyCredential(legacy, 1, slot1), timestamp, True)
if not legacy_creds[1] and slot2:
legacy_creds[1] = self.read_slot_otp(
LegacyCredential(legacy, 2, slot2), timestamp, True)
del legacy._device
if not key_found:
return None
# Add legacy slots first.
if legacy_creds[1]:
results.insert(0, legacy_creds[1])
if legacy_creds[0]:
results.insert(0, legacy_creds[0])
return results
def set_password(self, dev, password):
if dev.locked:
self.unlock(dev)
key = dev.calculate_key(password)
dev.set_key(key)
return key
def add_cred(self, dev, *args, **kwargs):
if dev.locked:
self.unlock(dev)
dev.put(*args, **kwargs)
def add_cred_legacy(self, *args, **kwargs):
legacy = self.open_otp()
if not legacy:
raise Exception('No YubiKey found!')
legacy.put(*args, **kwargs)
def delete_cred(self, dev, name):
if dev.locked:
self.unlock(dev)
dev.delete(name)
def delete_cred_legacy(self, slot):
legacy = self.open_otp()
if not legacy:
raise Exception('No YubiKey found!')
legacy.delete(slot)
def reset_device(self, dev):
dev.reset() | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/core/controller.py | controller.py |
from __future__ import print_function
from yubioath.yubicommon.compat import int2byte, byte2int
from Crypto.Hash import HMAC, SHA
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
try:
from urlparse import urlparse, parse_qs
from urllib import unquote
except ImportError:
from urllib.parse import unquote, urlparse, parse_qs
import subprocess
import struct
import time
import sys
import re
__all__ = [
'hmac_sha1',
'derive_key',
'der_pack',
'der_read',
'get_random_bytes'
]
#
# OATH related
#
def hmac_sha1(secret, message):
return HMAC.new(secret, message, digestmod=SHA).digest()
def time_challenge(t=None):
return struct.pack('>q', int((t or time.time())/30))
def parse_full(resp):
offs = byte2int(resp[-1]) & 0xf
return parse_truncated(resp[offs:offs+4])
def parse_truncated(resp):
return struct.unpack('>I', resp)[0] & 0x7fffffff
def format_code(code, digits=6):
return ('%%0%dd' % digits) % (code % 10 ** digits)
def parse_uri(uri):
uri = uri.strip() # Remove surrounding whitespace
parsed = urlparse(uri)
if parsed.scheme != 'otpauth': # Not a uri, assume secret.
return {'secret': uri}
params = dict((k, v[0]) for k, v in parse_qs(parsed.query).items())
params['name'] = unquote(parsed.path)[1:] # Unquote and strip leading /
params['type'] = parsed.hostname
if 'issuer' in params and not params['name'].startswith(params['issuer']):
params['name'] = params['issuer'] + ':' + params['name']
return params
#
# General utils
#
def derive_key(salt, passphrase):
if not passphrase:
return None
return PBKDF2(passphrase, salt, 16, 1000)
def der_pack(*values):
return b''.join([int2byte(t) + int2byte(len(v)) + v for t, v in zip(
values[0::2], values[1::2])])
def der_read(der_data, expected_t=None):
t = byte2int(der_data[0])
if expected_t is not None and expected_t != t:
raise ValueError('Wrong tag. Expected: %x, got: %x' % (expected_t, t))
l = byte2int(der_data[1])
offs = 2
if l > 0x80:
n_bytes = l - 0x80
l = b2len(der_data[offs:offs + n_bytes])
offs = offs + n_bytes
v = der_data[offs:offs + l]
rest = der_data[offs + l:]
if expected_t is None:
return t, v, rest
return v, rest
def b2len(bs):
l = 0
for b in bs:
l *= 256
l += byte2int(b)
return l
def kill_scdaemon():
try:
# Works for Windows.
from win32com.client import GetObject
from win32api import OpenProcess, CloseHandle, TerminateProcess
WMI = GetObject('winmgmts:')
ps = WMI.InstancesOf('Win32_Process')
for p in ps:
if p.Properties_('Name').Value == 'scdaemon.exe':
pid = p.Properties_('ProcessID').Value
print("Killing", pid)
handle = OpenProcess(1, False, pid)
TerminateProcess(handle, -1)
CloseHandle(handle)
except ImportError:
# Works for Linux and OS X.
pids = subprocess.check_output(
"ps ax | grep scdaemon | grep -v grep | awk '{ print $1 }'",
shell=True).strip()
if pids:
for pid in pids.split():
print("Killing", pid)
subprocess.call(['kill', '-9', pid])
NON_CCID_YK_PIDS = set([0x0110, 0x0113, 0x0114, 0x0401, 0x0402, 0x0403])
def ccid_supported_but_disabled():
"""
Check whether the first connected YubiKey supports CCID,
but has it disabled.
"""
if sys.platform in ['win32', 'cygwin']:
pids = _get_pids_win()
elif sys.platform == 'darwin':
pids = _get_pids_osx()
else:
pids = _get_pids_linux()
return bool(NON_CCID_YK_PIDS.intersection(pids))
def _get_pids_linux():
pid_pattern = re.compile(r' 1050:([0-9a-f]{4}) ')
pids = []
for line in subprocess.check_output('lsusb').splitlines():
match = pid_pattern.search(line.decode('ascii'))
if match:
pids.append(int(match.group(1), 16))
return pids
def _get_pids_osx():
pids = []
vid_ok = False
pid = None
output = subprocess.check_output(['system_profiler', 'SPUSBDataType'])
for line in output.splitlines():
line = line.decode().strip()
if line.endswith(':'): # New entry
if vid_ok and pid is not None:
pids.append(pid)
vid_ok = False
pid = None
if line.startswith('Vendor ID: '):
vid_ok = line.endswith(' 0x1050')
elif line.startswith('Product ID:'):
pid = int(line.rsplit(' ', 1)[1], 16)
return pids
def _get_pids_win():
pid_pattern = re.compile(r'PID_([0-9A-F]{4})')
pids = []
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_output(['wmic', 'path',
'Win32_USBControllerDevice', 'get', '*'],
startupinfo=startupinfo)
for line in output.splitlines():
if 'VID_1050' in line:
match = pid_pattern.search(line.decode('ascii'))
if match:
pids.append(int(match.group(1), 16))
return pids | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/core/utils.py | utils.py |
from __future__ import print_function
from .utils import time_challenge, parse_full, format_code
from .standard import TYPE_TOTP
from .exc import InvalidSlotError, NeedsTouchError
from yubioath.yubicommon.ctypes import CLibrary
from hashlib import sha1
from ctypes import (Structure, POINTER, c_int, c_uint8, c_uint, c_char_p,
c_bool, sizeof, create_string_buffer, cast, addressof)
import weakref
SLOTS = [
-1,
0x30,
0x38
]
YK_KEY = type('YK_KEY', (Structure,), {})
# Programming
SLOT_CONFIG = 1
SLOT_CONFIG2 = 3
CONFIG1_VALID = 1
CONFIG2_VALID = 2
YKP_CONFIG = type('YKP_CONFIG', (Structure,), {})
YK_CONFIG = type('YK_CONFIG', (Structure,), {})
YK_STATUS = type('YK_STATUS', (Structure,), {})
class YkPers(CLibrary):
_yk_errno_location = [], POINTER(c_int)
yk_init = [], bool
yk_release = [], bool
ykpers_check_version = [c_char_p], c_char_p
yk_open_first_key = [], POINTER(YK_KEY)
yk_close_key = [POINTER(YK_KEY)], bool
yk_challenge_response = [POINTER(YK_KEY), c_uint8, c_int, c_uint, c_char_p,
c_uint, c_char_p], bool
ykds_alloc = [], POINTER(YK_STATUS)
ykds_free = [POINTER(YK_STATUS)], None
ykds_touch_level = [POINTER(YK_STATUS)], c_int
yk_get_status = [POINTER(YK_KEY), POINTER(YK_STATUS)], c_int
ykp_alloc = [], POINTER(YKP_CONFIG)
ykp_free_config = [POINTER(YKP_CONFIG)], bool
ykp_configure_version = [POINTER(YKP_CONFIG), POINTER(YK_STATUS)], None
ykp_HMAC_key_from_raw = [POINTER(YKP_CONFIG), c_char_p], bool
ykp_set_tktflag_CHAL_RESP = [POINTER(YKP_CONFIG), c_bool], bool
ykp_set_cfgflag_CHAL_HMAC = [POINTER(YKP_CONFIG), c_bool], bool
ykp_set_cfgflag_HMAC_LT64 = [POINTER(YKP_CONFIG), c_bool], bool
ykp_set_extflag_SERIAL_API_VISIBLE = [POINTER(YKP_CONFIG), c_bool], bool
ykp_set_extflag_ALLOW_UPDATE = [POINTER(YKP_CONFIG), c_bool], bool
ykp_set_cfgflag_CHAL_BTN_TRIG = [POINTER(YKP_CONFIG), c_bool], bool
ykp_core_config = [POINTER(YKP_CONFIG)], POINTER(YK_CONFIG)
yk_write_command = [POINTER(YK_KEY), POINTER(YK_CONFIG), c_uint8, c_char_p
], bool
def yk_get_errno(self):
return self._yk_errno_location().contents.value
ykpers = YkPers('ykpers-1', '1')
YK_ETIMEOUT = 0x04
YK_EWOULDBLOCK = 0x0b
if not ykpers.yk_init():
raise Exception("Unable to initialize ykpers")
ykpers_version = ykpers.ykpers_check_version(None).decode('ascii')
class LegacyOathOtp(object):
"""
OTP interface to a legacy OATH-enabled YubiKey.
"""
def __init__(self, device):
self._device = device
def slot_status(self):
st = ykpers.ykds_alloc()
ykpers.yk_get_status(self._device, st)
tl = ykpers.ykds_touch_level(st)
ykpers.ykds_free(st)
return (
bool(tl & CONFIG1_VALID == CONFIG1_VALID),
bool(tl & CONFIG2_VALID == CONFIG2_VALID)
)
def calculate(self, slot, digits=6, timestamp=None, mayblock=0):
challenge = time_challenge(timestamp)
resp = create_string_buffer(64)
status = ykpers.yk_challenge_response(
self._device, SLOTS[slot], mayblock, len(challenge), challenge,
sizeof(resp), resp)
if not status:
errno = ykpers.yk_get_errno()
if errno == YK_EWOULDBLOCK:
raise NeedsTouchError()
raise InvalidSlotError()
return format_code(parse_full(resp.raw[:20]), digits)
def put(self, slot, key, require_touch=False):
if len(key) > 64: # Keys longer than 64 bytes are hashed, as per HMAC.
key = sha1(key).digest()
if len(key) > 20:
raise ValueError('YubiKey slots cannot handle keys over 20 bytes')
slot = SLOT_CONFIG if slot == 1 else SLOT_CONFIG2
key += b'\x00' * (20 - len(key)) # Keys must be padded to 20 bytes.
st = ykpers.ykds_alloc()
ykpers.yk_get_status(self._device, st)
cfg = ykpers.ykp_alloc()
ykpers.ykp_configure_version(cfg, st)
ykpers.ykds_free(st)
ykpers.ykp_set_tktflag_CHAL_RESP(cfg, True)
ykpers.ykp_set_cfgflag_CHAL_HMAC(cfg, True)
ykpers.ykp_set_cfgflag_HMAC_LT64(cfg, True)
ykpers.ykp_set_extflag_SERIAL_API_VISIBLE(cfg, True)
ykpers.ykp_set_extflag_ALLOW_UPDATE(cfg, True)
if require_touch:
ykpers.ykp_set_cfgflag_CHAL_BTN_TRIG(cfg, True)
if ykpers.ykp_HMAC_key_from_raw(cfg, key):
raise ValueError("Error setting the key")
ycfg = ykpers.ykp_core_config(cfg)
try:
if not ykpers.yk_write_command(self._device, ycfg, slot, None):
raise ValueError("Error writing configuration to key")
finally:
ykpers.ykp_free_config(cfg)
def delete(self, slot):
slot = SLOT_CONFIG if slot == 1 else SLOT_CONFIG2
if not ykpers.yk_write_command(self._device, None, slot, None):
raise ValueError("Error writing configuration to key")
class LegacyCredential(object):
def __init__(self, legacy, slot, digits=6):
self.name = 'YubiKey slot %d' % slot
self.oath_type = TYPE_TOTP
self.touch = None # Touch is unknown
self._legacy = legacy
self._slot = slot
self._digits = digits
def calculate(self, timestamp=None):
try:
return self._legacy.calculate(self._slot, self._digits, timestamp,
1 if self.touch else 0)
except NeedsTouchError:
self.touch = True
raise
else:
if self.touch is None:
self.touch = False
def delete(self):
self._legacy.delete(self._slot)
def __repr__(self):
return self.name
# Keep track of YK_KEY references.
_refs = []
def open_otp():
key = ykpers.yk_open_first_key()
if key:
key_p = cast(addressof(key.contents), POINTER(YK_KEY))
def cb(ref):
_refs.remove(ref)
ykpers.yk_close_key(key_p)
_refs.append(weakref.ref(key, cb))
return key
return None | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/core/legacy_otp.py | legacy_otp.py |
from __future__ import print_function, division
from .exc import CardError, DeviceLockedError, NoSpaceError
from .utils import (
der_read, der_pack, hmac_sha1, derive_key, get_random_bytes,
time_challenge, parse_truncated, format_code)
from yubioath.yubicommon.compat import int2byte, byte2int
import hashlib
import struct
import os
YKOATH_AID = b'\xa0\x00\x00\x05\x27\x21\x01\x01'
YKOATH_NO_SPACE = 0x6a84
INS_PUT = 0x01
INS_DELETE = 0x02
INS_SET_CODE = 0x03
INS_RESET = 0x04
INS_LIST = 0xa1
INS_CALCULATE = 0xa2
INS_VALIDATE = 0xa3
INS_CALC_ALL = 0xa4
INS_SEND_REMAINING = 0xa5
RESP_MORE_DATA = 0x61
TAG_NAME = 0x71
TAG_NAME_LIST = 0x72
TAG_KEY = 0x73
TAG_CHALLENGE = 0x74
TAG_RESPONSE = 0x75
TAG_T_RESPONSE = 0x76
TAG_NO_RESPONSE = 0x77
TAG_PROPERTY = 0x78
TAG_VERSION = 0x79
TAG_IMF = 0x7a
TAG_ALGO = 0x7b
TAG_TOUCH_RESPONSE = 0x7c
TYPE_MASK = 0xf0
TYPE_HOTP = 0x10
TYPE_TOTP = 0x20
ALG_MASK = 0x0f
ALG_SHA1 = 0x01
ALG_SHA256 = 0x02
PROP_ALWAYS_INC = 0x01
PROP_REQUIRE_TOUCH = 0x02
SCHEME_STANDARD = 0x00
SCHEME_STEAM = 0x01
STEAM_CHAR_TABLE = "23456789BCDFGHJKMNPQRTVWXY"
def format_code_steam(int_data, digits):
chars = []
for i in range(5):
chars.append(STEAM_CHAR_TABLE[int_data % len(STEAM_CHAR_TABLE)])
int_data //= len(STEAM_CHAR_TABLE)
return ''.join(chars)
def ensure_unlocked(ykoath):
if ykoath.locked:
raise DeviceLockedError()
def format_truncated(t_resp, scheme=SCHEME_STANDARD):
digits, data = byte2int(t_resp[0]), t_resp[1:]
int_data = parse_truncated(data)
if scheme == SCHEME_STANDARD:
return format_code(int_data, digits)
elif scheme == SCHEME_STEAM:
return format_code_steam(int_data, digits)
def hmac_shorten_key(key, algo):
if algo == ALG_SHA1:
h = hashlib.sha1()
elif algo == ALG_SHA256:
h = hashlib.sha256()
else:
raise ValueError('Unsupported algorithm!')
if len(key) > h.block_size:
key = h.update(key).digest()
return key
class Credential(object):
"""
Reference to a credential.
"""
def __init__(self, ykoath, oath_type, name, touch=False):
self._ykoath = ykoath
self.oath_type = oath_type
self.name = name
self.touch = touch
def calculate(self, timestamp=None):
return self._ykoath.calculate(self.name, self.oath_type, timestamp)
def delete(self):
self._ykoath.delete(self.name)
def __repr__(self):
return self.name
class _426Device(object):
"""
The 4.2.0-4.2.6 firmwares have a known issue with credentials that require
touch: If this action is performed within 2 seconds of a command resulting
in a long response (over 54 bytes), the command will hang. A workaround is
to send an invalid command (resulting in a short reply) prior to the
"calculate" command.
"""
def __init__(self, delegate):
self._delegate = delegate
self._long_resp = False
def __getattr__(self, name):
return getattr(self._delegate, name)
def send_apdu(self, cl, ins, p1, p2, data):
if ins == INS_CALCULATE and self._long_resp:
self._delegate.send_apdu(0, 0, 0, 0, '')
self._long_resp = False
resp, status = self._delegate.send_apdu(cl, ins, p1, p2, data)
self._long_resp = len(resp) > 52 # 52 bytes resp, 2 bytes status...
return resp, status
class YubiOathCcid(object):
"""
Device interface to a OATH-enabled YubiKey.
"""
def __init__(self, device):
self._device = device
self._select()
if (4, 2, 0) <= self.version <= (4, 2, 6):
self._device = _426Device(device)
def _send(self, ins, data='', p1=0, p2=0, expected=0x9000):
resp, status = self._device.send_apdu(0, ins, p1, p2, data)
while (status >> 8) == RESP_MORE_DATA:
more, status = self._device.send_apdu(
0, INS_SEND_REMAINING, 0, 0, '')
resp += more
if status == YKOATH_NO_SPACE:
raise NoSpaceError()
if expected != status:
raise CardError(status)
return resp
def _select(self):
resp = self._send(0xa4, YKOATH_AID, p1=0x04)
self._version, resp = der_read(resp, TAG_VERSION)
self._id, resp = der_read(resp, TAG_NAME)
if len(resp) != 0:
self._challenge, resp = der_read(resp, TAG_CHALLENGE)
else:
self._challenge = None
@property
def id(self):
return self._id
@property
def version(self):
return tuple(byte2int(d) for d in self._version)
@property
def locked(self):
return self._challenge is not None
def delete(self, name):
data = der_pack(TAG_NAME, name.encode('utf8'))
self._send(INS_DELETE, data)
def calculate(self, name, oath_type, timestamp=None):
challenge = time_challenge(timestamp) \
if oath_type == TYPE_TOTP else b''
data = der_pack(
TAG_NAME, name.encode('utf8'), TAG_CHALLENGE, challenge)
resp = self._send(INS_CALCULATE, data)
# Manual dynamic truncation required for Steam entries
resp = der_read(resp, TAG_RESPONSE)[0]
digits, resp = resp[0:1], resp[1:]
offset = byte2int(resp[-1]) & 0xF
resp = resp[offset:offset + 4]
scheme = SCHEME_STEAM if name.startswith('Steam:') else SCHEME_STANDARD
return format_truncated(digits + resp, scheme)
def calculate_key(self, passphrase):
return derive_key(self.id, passphrase)
def unlock(self, key):
if not self.locked:
return
response = hmac_sha1(key, self._challenge)
challenge = get_random_bytes(8)
verification = hmac_sha1(key, challenge)
data = der_pack(TAG_RESPONSE, response, TAG_CHALLENGE, challenge)
resp = self._send(INS_VALIDATE, data)
resp = der_read(resp, TAG_RESPONSE)[0]
if resp != verification:
raise ValueError('Response did not match verification!')
self._challenge = None
def set_key(self, key=None):
ensure_unlocked(self)
if key:
keydata = int2byte(TYPE_TOTP | ALG_SHA1) + key
challenge = get_random_bytes(8)
response = hmac_sha1(key, challenge)
data = der_pack(TAG_KEY, keydata, TAG_CHALLENGE, challenge,
TAG_RESPONSE, response)
else:
data = der_pack(TAG_KEY, b'')
self._send(INS_SET_CODE, data)
def reset(self):
self._send(INS_RESET, p1=0xde, p2=0xad)
self._challenge = None
def list(self):
ensure_unlocked(self)
resp = self._send(INS_LIST)
items = []
while resp:
data, resp = der_read(resp, TAG_NAME_LIST)
items.append(Credential(
self,
TYPE_MASK & byte2int(data[0]),
data[1:],
None
))
return items
def calculate_all(self, timestamp=None):
ensure_unlocked(self)
data = der_pack(TAG_CHALLENGE, time_challenge(timestamp))
resp = self._send(INS_CALC_ALL, data, p2=1)
results = []
while resp:
name, resp = der_read(resp, TAG_NAME)
name = name.decode('utf8')
tag, value, resp = der_read(resp)
if name.startswith('_hidden:') and 'YKOATH_SHOW_HIDDEN' \
not in os.environ:
pass # Ignore hidden credentials.
elif tag == TAG_T_RESPONSE:
# Steam credentials need to be recalculated
# to skip full truncation done by Yubikey 4.
code = self.calculate(name, TYPE_TOTP) \
if name.startswith('Steam:') \
else format_truncated(value, SCHEME_STANDARD)
results.append((
Credential(self, TYPE_TOTP, name, False),
code
))
elif tag == TAG_TOUCH_RESPONSE:
results.append((
Credential(self, TYPE_TOTP, name, True),
None
))
elif tag == TAG_NO_RESPONSE:
results.append((Credential(self, TYPE_HOTP, name), None))
else:
print("Unsupported tag: %02x" % tag)
results.sort(key=lambda a: a[0].name.lower())
return results
def put(self, name, key, oath_type=TYPE_TOTP, algo=ALG_SHA1, digits=6,
imf=0, always_increasing=False, require_touch=False):
ensure_unlocked(self)
key = hmac_shorten_key(key, algo)
keydata = int2byte(oath_type | algo) + int2byte(digits) + key
data = der_pack(TAG_NAME, name.encode('utf8'), TAG_KEY, keydata)
properties = 0
if always_increasing:
properties |= PROP_ALWAYS_INC
if require_touch:
if self.version < (4, 2, 6):
raise Exception("Touch-required not supported on this key")
properties |= PROP_REQUIRE_TOUCH
if properties:
data += int2byte(TAG_PROPERTY) + int2byte(properties)
if imf > 0:
data += der_pack(TAG_IMF, struct.pack('>I', imf))
self._send(INS_PUT, data)
return Credential(self, oath_type, name) | yubioath-desktop | /yubioath-desktop-3.1.0.tar.gz/yubioath-desktop-3.1.0/yubioath/core/standard.py | standard.py |
YubiStack
=========
YubiStack provides a python re-implementation of:
* `yubiauth <https://github.com/Yubico/yubiauth>`_: Authentication client with a simple user management system
* `yubikey-val <https://github.com/Yubico/yubikey-val>`_: YubiKey validation server
* `yubikey-ksm <https://github.com/Yubico/yubikey-ksm>`_: YubiKey key storage module
NOTE: Only the authentication part is implemented from yubiauth, the user management system is NOT.
Installation
------------
To install yubistak, simply:
.. code-block:: bash
$ sudo pip install yubistack
Configuration
-------------
The configuration file path is read from YUBISTACK_SETTINGS environment variable, otherwise defaults
to /etc/yubistack.conf. You can find a sample config in the repo.
| yubistack | /yubistack-0.5.5.tar.gz/yubistack-0.5.5/README.rst | README.rst |
yubistorm
=========
Pure python module that provides async calls for the YubiCloud
authentication servers (
https://www.yubico.com/products/services-software/yubicloud/ ) API
and works with tornado.
This project provides the yubistorm.YubiStorm class that implements
API calls for the YubiKey validation protocol (
https://developers.yubico.com/yubikey-val/Validation_Protocol_V2.0.html )
and lets you easily create a web server that authenticates users with
two factor authentication. This is an asynchronous library that works
with tornado's ioloop. High level methods of the yubistorm.YubiStorm
class are awaitable, and can be used in a non-blocking way.
Documentation
-------------
http://pythonhosted.org/yubistorm/
Installation
------------
Please note that this version works with tornado 4.3 only! Below version
4.3, tornado does not support asnyc def statements. The 4.3 version
is now available from PyPi.
pip3 install tornado
pip3 install yubistorm
License
-------
Yubistorm is distributed under the GNU LGPL v3 license.
http://www.gnu.org/licenses/lgpl-3.0.html
Changelog
---------
v0.1.0 - Initial beta version
Getting Started
---------------
The YubiCould API lets you authenticate users with a YubiKey hardware
device. Beside authentication, the API returns the unique identifier
of the hardware key that can be assigned to a local user, and it can
be used to identify the user that wants to log in. To implement two
factor authentication, you also need to add another factor (for example,
check a secret password or do a challenge/response).
Get your API credentials
........................
To get a new API client id and key, go to https://upgrade.yubico.com/getapikey/ and follow instructions.
You must **make sure** that you wait at least 5 minutes before you try to use a newly requested API key.
In fact, my experience is that sometimes it can take 15-30 minutes before all YubiCloud servers are
synchronized.
Making API calls
................
First, you need to create a client:
import yubistorm
client = yubistorm.YubiStorm(client_id=YOUR_CLIENT_ID, secret_key=YOUR_SECRET_KEY)
Then you can verify the otp inside a tornado http(s) request:
otp = request.get_argument("otp")
yubikey_id = await client.authenticate(otp) # Use the id to identify the user
Use the example server for the know-how
.......................................
Check out the repostory from bitbucket, and start a test server in less them 5 minutes. Try the test server, and
check the source to see how to use YubiCloud authentication from a working tornado server:
hg clone https://bitbucket.org/nagylzs/yubistorm
cd yubistorm/test
cp local.py.default local.py # also edit and put your app client id and secret here
python3.5 main.py # and then point your browser to port :8080
Resources
---------
* Check out the Tornado API docs ( http://tornadokevinlee.readthedocs.org/en/latest/ ).
* Check out the YubiCloud validation protocol ( https://developers.yubico.com/yubikey-val/Validation_Protocol_V2.0.html ).
| yubistorm | /yubistorm-0.1.1.zip/yubistorm-0.1.1/README.txt | README.txt |
import copy
import sys
import random
import base64
import uuid
import urllib.parse
from hashlib import sha1
import hmac
import tornado
import tornado.httpclient
import tornado.concurrent
import tornado.ioloop
if sys.version_info[0] < 3 or sys.version_info[1] < 5:
raise Exception("YubiStorm requires at least Python version 3.5.")
if tornado.version < "4.3":
raise Exception("YubiStorm requires at least tornado version 4.3.")
__version__ = "0.1.1"
class YubiStormError(Exception):
"""Raised for all kinds errors, that are above the https level.
.. note::
For http level errors, tornado.httpclient.HTTPError is raised instead.
"""
pass
class YubiStormAPIError(YubiStormError):
"""Raised when YubiCloud API call returns an error.
Instances of this class mean that they YubiCloud server already responded, and returned a status
code that indicates a problem detected on the server side."""
pass
class YubiStormSecurityBreachError(YubiStormError):
"""Raised when the client library detects possible security breach.
Instances of this class mean that they YubiCloud server already responded, but there is a problem with the
response: the client side detected a possible security breach."""
pass
class YubiStorm(object):
"""Asynchronous YubiCloud authentication client that works with tornado."""
"""Clear this flag to disable validation of SSL certificates. (You should **NEVER** clear this flag.)"""
validate_cert = True
"""User agent to be used for making requests to YubiCloud servers."""
user_agent = "YubiStorm %s" % __version__
"""YubiCloud API servers."""
api_servers = [
"api.yubico.com",
"api2.yubico.com",
"api3.yubico.com",
"api4.yubico.com",
"api5.yubico.com",
]
api_path = "/wsapi/2.0/"
def __init__(self, client_id, client_secret, logger=None):
"""
:param client_id: Your client id for your application.
:param client_secret: Your base64 encoded API secret password for your custom application.
:param logger: A logger object that will be used for logging.
"""
self.http_client = tornado.httpclient.AsyncHTTPClient(defaults=dict(user_agent=self.user_agent))
self.client_id = client_id
self.client_secret = base64.b64decode(client_secret)
self.logger = logger
@classmethod
def _create_new_nonce(cls):
"""Create a new unique unpredictable identifier.
Used for the nonce parameter of YubiCloud API call.
.. note::
Although it is undocumented, the nonce parameter cannot contain any character that is escaped
with % code in the GET request. For this reason, we are returning a hex digest here.
"""
return uuid.uuid4().hex
def create_signature(self, params):
"""Create HMAC_SHA1 signature for a query.
:param params: A dict of GET parameter/name pairs.
:return: The base64 encoded HMAC signature, as required by the YubiKey validation protocol.
Please note that the returned value is **not a binary string**. It is a normal str instance.
:rtype: str
"""
data = []
for key in sorted(params.keys()):
data.append("%s=%s" % (key, params[key]))
data = "&".join(data)
if self.logger:
self.logger.debug("create_signature: data: %s" % repr(data))
hashed = hmac.new(self.client_secret, data.encode("ascii"), sha1)
return base64.encodebytes(hashed.digest()).rstrip(b'\n').decode("ascii")
def verify_signature(self, params):
"""Verify signature for a response.
:param params: A dict of values as returned by the YubiCloud server.
It should contain the hmac signature under the "h" key.
:return: True if the signature was correct, False otherwise.
"""
assert "h" in params
bare = copy.copy(params)
del bare["h"]
good_signature = self.create_signature(bare)
if self.logger:
self.logger.debug("verify_signature: %s", good_signature == params["h"])
return good_signature == params["h"]
def _add_query_params(self, url, params, add_signature=True):
"""Add parameters to a GET url.
:param url: The original GET url.
:param params: A dict of parameters (name,value pairs)
:param add_signature: When set, the HMAC-SHA1 signature will be added. (See YubiKey validation protocol.)
:return: The modified url.
Please note that this method does not support multiple values for the same parameter!
"""
url_parts = list(urllib.parse.urlparse(url))
query = dict(urllib.parse.parse_qsl(url_parts[4]))
query.update(params)
if add_signature:
if "h" in query:
del query["h"]
query["h"] = self.create_signature(query)
if self.logger:
self.logger.debug("_add_query_params: %s", str(query))
url_parts[4] = urllib.parse.urlencode(query)
return urllib.parse.urlunparse(url_parts)
async def get(self, rel_url, params, add_signature=True):
"""Get from YubiCloud.
:param rel_url: URL relative path to api_path
:param params: a dict of GET parameter values to be added to the GET url
:param add_signature: Set flag to add hmac signature as parameter "h"
:return: a response object
This method sends a https GET request to one of the yubicloud servers and returns the response object.
The server is selected randomly from ``api_servers``.
This is an async method. You need to ``await`` for it. Do not call synchronously.
"""
assert ("/" not in rel_url)
server_host = random.choice(self.api_servers)
api_url = "https://" + server_host + self.api_path
url = self._add_query_params(api_url + rel_url, params, add_signature=add_signature)
if self.logger:
self.logger.debug("get: awaiting GET %s", url)
request = tornado.httpclient.HTTPRequest(url=url, method="GET", validate_cert=self.validate_cert)
response = await self.http_client.fetch(request)
if self.logger:
self.logger.debug("get: completed GET %s, code=%s reason='%s'", url, response.code, response.reason)
if response.error:
response.rethrow()
else:
return response
async def get_and_parse(self, rel_url, params, add_signature=True):
"""Get from YubiCloud server and parse text response.
:param rel_url: URL relative to api_url
:param params: a dict of GET parameter values to be added to the GET url
:param add_signature: Set flag to add hmac signature as parameter "h". Increases security (the server can
verify the authenticity of the client).
:return: a data structure, parsed from the response body text.
This is an async method. You need to ``await`` for it. Do not call synchronously.
**IMPORTANT:** before you use the response, you must also call verify_signature on it!
"""
response = await self.get(rel_url, params, add_signature=add_signature)
if self.logger:
self.logger.debug("get_and_parse: response body:%s", response.body)
txt = response.body.decode("UTF-8")
result = {}
for line in txt.split("\n"):
line = line.strip()
idx = line.find("=")
assert idx
name, value = line[:idx], line[idx + 1:]
if name:
result[name] = value
# if not self.verify_signature(result):
# raise YubiStormSecurityBreachError("Signature verification failed on the server response.")
return result
@classmethod
def is_valid_otp(cls, otp):
"""Check if the given otp value is an otp string that has a valid format.
:param otp: A string containing the one time password, obtained from the YubiKey.
Unfortunately, the modhex format used by YubiKey can be altered by a Drovak-based keyboard.
YubiCo's recommendation is that we only check that the otp has 32-48 printable characters.
"""
if isinstance(otp, str) and (32 <= len(otp) <= 48):
return otp.isprintable()
else:
return False
@classmethod
def get_yubikey_id(cls, otp):
"""Get the unique identifier of a YubiKey from an otp.
:param otp: A string containing the one time password, obtained from the YubiKey.
Each YubiKey has a fixed unique identifier that is contained within the generated OTP. The YubiCloud service
uses this identifier to identify the key, and store otp usage, detect replay attacks etc.
This method extracts the unique identifier of the YubiKey from an otp generated with it. This identifier can
be used assign the YubiKey to a user. Then it will be possible to find the user by giving just a single
otp string (e.g. username input is not needed).
"""
if not cls.is_valid_otp(otp):
raise YubiStormAPIError("Invalid OTP: should be a printable string of 32-48 characters.")
return otp[:-32]
async def verify(self, otp, sl="secure"):
"""Veryify OTP value with YubiCloud server.
:param otp: OTP value provided by a YubiKey hardware device.
:param sl: securelevel value. When given, this should be an integer between 0 and 100,
indicating percentage of syncing required by client. You can also use strings "fast" or "secure"
to use server-configured values. If absent, let the server decide.
:return: Returns a dict that contains a subset of the response from the server. Keys in the response:
* id - unique identifier of the yubikey
* timestamp - YubiKey internal timestamp when the key was pressed
* sessioncounter - YubiKey internal usage counter when key was pressed.
This will be a strictly increasing number that shows how many times the key was
pressed since it was first programmed.
* sessionuse - YubiKey internal session usage counter when key was pressed
* sl - percentage of external validation server that replied successfully (0 to 100)
.. note::
* When YubiCloud servers are not available, this method will raise a tornado.httpclient.HTTPError
* When authentication is unsuccessful, this method will raise a YubiStormAPIError.
"""
if not self.is_valid_otp(otp):
raise YubiStormAPIError("Invalid OTP: should be a printable string of 32-48 characters.")
nonce = self._create_new_nonce()
params = {
"id": self.client_id,
"otp": otp,
"nonce": nonce,
"timestamp": "1",
}
if sl:
if isinstance(sl, int):
assert 0 <= sl <= 100
else:
assert sl in {"secure", "fast"}
params["sl"] = sl
result = await self.get_and_parse("verify", params)
if result["status"].lower() != "ok":
raise YubiStormAPIError(result["status"])
if not self.verify_signature(result):
raise YubiStormSecurityBreachError("Signature verification failed on the server response.")
if result["nonce"] != nonce:
raise YubiStormSecurityBreachError("Possible hijack of server response: nonce parameter was modified.")
if result["otp"] != otp:
raise YubiStormSecurityBreachError("Possible hijack of server response: otp parameter was modified.")
return {
"id": self.get_yubikey_id(otp),
"timestamp": result["timestamp"],
"sessioncounter": result["sessioncounter"],
"sessionuse": result["sessionuse"],
"sl": result["sl"],
} | yubistorm | /yubistorm-0.1.1.zip/yubistorm-0.1.1/yubistorm.py | yubistorm.py |
from django.db import migrations, models
import django.utils.timezone
def set_apikey_labels(apps, schema_editor):
APIKey = apps.get_model('yubival', 'APIKey')
db_alias = schema_editor.connection.alias
for api_key in APIKey.objects.using(db_alias).all():
api_key.label = 'Label %d' % api_key.id
api_key.save()
def set_device_labels(apps, schema_editor):
Device = apps.get_model('yubival', 'Device')
db_alias = schema_editor.connection.alias
for device in Device.objects.using(db_alias).all():
device.label = 'Label %d' % device.id
device.save()
class Migration(migrations.Migration):
dependencies = [
('yubival', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='apikey',
name='date_created',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='apikey',
name='label',
field=models.CharField(max_length=64, null=True),
preserve_default=False,
),
migrations.RunPython(set_apikey_labels, migrations.RunPython.noop),
migrations.AlterField(
model_name='apikey',
name='label',
field=models.CharField(max_length=64, unique=True, null=False),
preserve_default=False,
),
migrations.AddField(
model_name='device',
name='date_created',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='device',
name='label',
field=models.CharField(max_length=64, null=True),
preserve_default=False,
),
migrations.RunPython(set_device_labels, migrations.RunPython.noop),
migrations.AlterField(
model_name='device',
name='label',
field=models.CharField(max_length=64, unique=True, null=False),
preserve_default=False,
),
] | yubival | /migrations/0002_add_label_and_date_created_fields.py | 0002_add_label_and_date_created_fields.py |
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>. | yubundle | /yubundle-0.0.2.tar.gz/yubundle-0.0.2/LICENSE.md | LICENSE.md |
# YUCC - Your UpCloud CLI
A CLI for the UpCloud API. Still a work in progress.
## Installation and configuration
### Install from source
Clone the repository and run `pip install .`, either globally or in a virtual
environment.
### Install from PyPI
Run `pip install yucc`. You may need to prepend the command with `sudo`
### Configuration
The CLI makes use of a hidden `.yuccrc`-file in your home directory. This is an
example of what it looks like:
```
[default]
username = user
password = passw0rd
default_zone = de-fra1
[profile2]
username = other_user
password = passw0rd
```
This file defines profiles for the CLI to use. If none is specified, it uses
`default` (by default). Make shure this file is accessible only by your user
(600 permissions), as it does contain sensitive information.
Run `yucc --help` or `yucc -h` to get a glimpse of what the tool offers.
## Usage
To list the plans that are available, type: `yucc ls plans`
To list the zones that are available, type: `yucc ls zones`
To create a server, do something like this:
```bash
yucc server create --hostname server1 --plan 1xCPU-1GB \
--os "CentOS 7.0" \
--login-user user --ssh-key ssh_public_key_file.pub \
--ensure-started
```
The tool returns the UUID of the created server. The server is created in the
default zone specified in the default profile. To override the zone, add the
`--zone <zone>` parameter.
To restart an existing server, type: `yucc server restart <uuid>`
To stop an existing server, type: `yucc server stop <uuid>`
To remove an existing server, type: `yucc server delete <uuid>`. To also delete
storage devices associated with the server, add the `--delete-storages` flag.
To list all servers, run: `yucc ls servers`.
## Todo
- Add tags on server creation
- IP address management, including listing IPs, assigning, etc...
- Storage management, attaching, detaching, etc...
## Contributing
If you feel a feature is missing, find a bug or have any suggestions, please
feel free to create an issue or open a pull request :)
## License
The project is MIT licensed.
| yucc | /yucc-0.8.3.tar.gz/yucc-0.8.3/README.md | README.md |
## yucctools
常用的工具分享。可以方便的调用本工具去记录日志等。
### 安装
方法一:直接使用pip安装
```python
pip install yucctools
```
方法二:国内pip有时较慢,可以指定使用清华源安装
```python
pip install yucctools -i https://pypi.tuna.tsinghua.edu.cn/simple
```
### 使用示例
#### 日志工具
可以方便的去初始化记录日志,并记录日志,样例:
```python
# 导入包
import yucctools as yt
# 初始化logger实例
logger = yt.logger(filepath='test.log')
# 记录信息,只要这么调用就可以使用了
# 记录一条debug级别的日志
logger.info('this is a debug levle log.')
# 记录一条info级别的日志
logger.info('this is a info level log.')
# 记录一条warning级别的日志记录
logger.warning('this is a warning level log.')
# 记录一条error级别的日志记录
logger.error('this is a error level log.')
# 记录一条critical级别的日志记录
logger.critical('this is a critical level log.')
```
### 附录
github网页:https://github.com/yucc2018/yucctools
pypi网页:https://pypi.org/project/yucctools/
| yucctools | /yucctools-0.1.9.tar.gz/yucctools-0.1.9/README.md | README.md |
import sys
import click
from .base import AliasedGroup
from yucebio.yc2.adaptor.util.config import Config
# from yucebio_wdladaptor.backend_v2 import SUPPORTTED_BACKENDS, create_adaptor, PLACEHOLDER_SIMG_PATH, PLACEHOLDER_GLOBAL_PATH, BaseAdaptor
from yucebio.yc2.adaptor.backend import create_adaptor
@click.group('adaptor', cls=AliasedGroup)
def cli():
"""WDL适配器"""
pass
def info(msg, file=sys.stderr, **secho_options):
click.secho(msg, fg='red', file=file, **secho_options)
@cli.command()
@click.option('--backend_name', '-b', required=True, type=str, help="平台配置名称")
@click.argument('json', nargs=-1)
def submit(**kw):
"""通过“WDL流程对应的模板”创建通用流程到指定平台(适用于生产人员,需要自行上传fastq)
JSON 一个或多个任意通用流程对应的JSON文件
Tips:
标准模板:使用wdl定义流程时,流程开发人员会同时提供一份包含流程所需数据的JSON模板。使用人员基于实际场景修改JSON模板的值,然后将修改后的JSON文件投递到YC2中。
使用人员不得新增字段,不得修改字段值的类型,只能基于字段类型提供新的数据。若对应字段为文件,使用人员必须确保文件已经存在。
`yc2_wdl api submit`提供了按照标准数据格式提交作业的方式,可以支持数据下机前投递任务的使用场景
"""
api = Config().api
for jsonfile in kw["json"]:
try:
msg = api.submit(kw['backend_name'], jsonfile)
except Exception as e:
click.secho(f"任务信息上传失败:{e},请手动将作业信息上传到服务器或联系开发人员", fg='red', file=sys.stderr)
else:
click.secho(f"上传成功: {msg}", fg="green")
@cli.command()
def pre_submit(**kw):
"""通过“标准数据格式”创建通用流程(适用于生产人员,由YC2自动完成数据上传工作)
JSON: 适用于V2版本的JSON文件。其中包含模板、样本、分析流程、动态监控基本信息。后台会自动上传数据
参考:http://gitlab.yucebio.com/python-packages/wdl_api/tree/bug/workflow#%E6%8E%A5%E5%8F%A3-version-2
"""
api = Config().api
for jsonfile in kw["json"]:
try:
msg = api.submit_by_standrand_data(jsonfile)
except Exception as e:
click.secho(f"任务信息上传失败:{e},请手动将作业信息上传到服务器或联系开发人员", fg='red', file=sys.stderr)
else:
click.secho(f"上传成功: {msg}", fg="green")
@cli.command()
@click.option('--prefix', '-p', type=str, help="用户自定义的分析编号")
@click.option('--cromwell_id', '-c', type=str, help="Cromwell自动生成的编号")
@click.option("--backend_name", "-b", required=True, type=str, help="平台配置名称")
def restart(prefix, cromwell_id, backend_name):
"""重投作业。请至少提供prefix或cromwell_id参数(仅适用于生产人员)
Tips: 使用非通用流程的研发人员请使用convert子命令投递或重新投递任务
"""
if prefix and cromwell_id:
return info("只能使用一种编号")
if not prefix and not cromwell_id:
return info("至少指定一种编号")
api = Config().api
try:
msg = api.submit_action('restart', {"backend_name": backend_name}, prefix if prefix else cromwell_id)
except Exception as e:
info(e)
else:
click.secho(msg, fg="green")
@cli.command()
@click.option('--prefix', '-p', type=str, help="用户自定义的分析编号")
@click.option('--cromwell_id', '-c', type=str, help="Cromwell自动生成的编号")
@click.option("--backend_name", "-b", required=True, type=str, help="平台配置名称")
def abort(prefix, cromwell_id, backend_name):
"""根据cromwell_id或prefix终止作业
Tips: 同一个prefix可能会存在多个作业, 此时会因找不到正确的作业而失败
"""
if prefix and cromwell_id:
return info("只能使用一种编号")
if not prefix and not cromwell_id:
return info("至少指定一种编号")
api = Config().api
try:
msg = api.submit_action('abort', {"backend_name": backend_name}, prefix if prefix else cromwell_id)
except Exception as e:
info(e)
else:
click.secho(msg, fg="green")
@cli.command()
@click.option("--input", "-i", required=False, help="input json file")
@click.option("--backend_name", "-b", required=True, type=str, help="平台配置名称")
@click.option("--submit", "-s", is_flag=True, default=False, help="是否自动投递。(默认情况下会将适配后的内容保存到本地,由使用人员手动投递)")
@click.option('--runtimes', '-r', help=f"配置需要自动添加到task.runtime中的属性", type=str)
@click.argument("wdl")
def convert(**kw):
"""根据不同平台具有的基础设施转换通用WDL,并自动适配json和task。(适用于研发人员)
"""
config = Config()
backend = config.get_backend_config(kw["backend_name"])
adaptor = create_adaptor(backend)
adaptor.parse(wdl_path=kw['wdl'], input_path=kw['input'], runtimes=kw["runtimes"])
adaptor.convert()
if not kw['submit']:
adaptor.generate_file(outdir='temp')
return
jobid = adaptor.submit()
click.secho(f"submit success: {jobid},准备将任务信息上传到到服务器", fg="green")
# 若配置了API,则将任务发送到API服务器
api = config.api
try:
msg = api.submit_action('link', {"cromwell_id": jobid, "backend_name":kw['backend_name']})
except Exception as e:
click.secho(f"任务信息上传失败:{e},请手动将作业信息上传到服务器或联系开发人员", fg='red', file=sys.stderr)
else:
click.secho(f"上传成功: {msg}", fg="green")
@cli.command()
@click.option("--access_id", "-i", help="阿里云ACCESS KEY ID")
@click.option('--access_secrect', '-s', help="阿里云ACCESS KEY SECRECT")
def update_bcs_instance(access_id, access_secrect):
"""更新阿里云可用类型
"""
import batchcompute, datetime
bNeedUpdateAccess = True
# adaptor = BaseAdaptor()
config = Config()
if not (access_id and access_secrect):
# 从配置文件中获取
# cfg = adaptor.config("bcs_access", {})
cfg = config.get("bcs_access", {})
if not cfg:
click.secho("请提供ACCESS_KEY_ID和ACCESS_KEY_SECRECT", fg='yellow')
return
access_id, access_secrect = cfg.get("access_id", ""), cfg.get("access_secrect", "")
bNeedUpdateAccess = True
if not (access_id and access_secrect):
return
try:
client = batchcompute.Client(batchcompute.CN_SHENZHEN, access_id, access_secrect)
response = client.get_available_resource()
except Exception as e:
click.secho(f"Error: {e.code} 请检查ACCESS_KEY_ID[{repr(access_id)}]和ACCESS_KEY_SECRECT[{repr(access_secrect)}]是否正确", fg='red')
return
if bNeedUpdateAccess:
config.set("bcs_access", {"access_id": access_id, "access_secrect": access_secrect})
data = response.content
data['updated_at'] = datetime.datetime.now().strftime("%Y-%m-%d")
config.set("available_bcs_rescource", data)
click.secho("阿里云可用实例类型更新完毕!")
if __name__ == "__main__":
cli() | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/command/adaptor.py | adaptor.py |
import click
import datetime
from click.types import DateTime
from .base import AliasedGroup
from yucebio.yc2.adaptor.util.monitor import Monitor
@click.group('monitor', cls=AliasedGroup)
def cli():
"""作业监控"""
pass
@cli.command()
@click.option('--page', '-p', help="分页页码", type=int, default=1, show_default=True)
@click.option('--page_size', '-ps', help="每页查询的数据量", type=int, default=50, show_default=True)
@click.option('--backend_name', '-b', help="按Cromwell配置过滤")
@click.option('--prefix', help="按prefix(分析任务编号)模糊查询")
@click.option('--sample_ids', '-sa', help="按样本编号模糊查询")
@click.option('--status', '-s', help="按作业状态查询", type=str)
@click.option('--detail', '-d', is_flag=True, default=False, help="显示详细信息(错误信息和当前运行中的步骤)", show_default=True)
def ls(**kw):
"""查看本人提交的任务最新状态
固定展示以下列
- Status: Ready/Waitdata(准备中,等待下机),Uploading(上传数据),Init(准备投递到Cromwell),Running,Finish,Aborted,Failed
- Task_Count: 正在运行的任务数/运行中+已结束的任务数/总任务数
- Workdir: 作业在Cromwell集群上的工作目录
- Start/Duration:开始时间和分析时长(保留2位小数的小时)
- Prefix/Project: Prefix/分析项目编号。若Project相同与Prefix相同,则简写为"-"
- Samples:按照 tumor/normal/rna的顺序展示样本编号
- WorkflowName: 流程名称
- Metadata: Cromwell Metadata链接地址
"""
monitor = Monitor(backend_name=kw['backend_name'])
show_detail = kw.pop('detail')
monitor.list_jobs(kw, show_detail=bool(show_detail))
@cli.command()
@click.option('--backend_name', '-b', help="cromwell server 配置名称", required=True)
@click.option('--id', '-j', help="cromwell 作业编号")
@click.option('--name', '-n', help="cromwell 流程名称")
@click.option('--status', '-s', help="cromwell 作业状态", type=click.Choice(['Submitted', 'Running', 'Aborting', 'Failed', 'Succeeded', 'Aborted']))
@click.option('--start', '-st', help="cromwell 开始时间", type=DateTime())
@click.option('--submission', '-su', help="cromwell 提交时间", type=DateTime())
@click.option('--page', '-p', help="分页页码", type=int)
@click.option('--pageSize', '-ps', help="每页查询的数据量", type=int)
@click.option('--save', help="是否保存到API服务器", is_flag=True, default=False)
def query(**kw):
"""基于Cromwell API接口查询所有任务基本信息
参考: https://cromwell.readthedocs.io/en/stable/api/RESTAPI/#workflowqueryparameter
"""
server = kw.pop('backend_name')
params = {k:v for k,v in kw.items() if v and k != 'save'}
for k in ['start', 'submission']:
if not kw[k]:
continue
t: datetime.datetime = kw[k]
params[k] = t.strftime('%Y-%m-%dT%H:%M:%S.000Z')
if not params:
ctx = click.get_current_context()
click.secho('请至少指定一种参数', fg='red')
print(ctx.get_help())
return
monitor = Monitor(backend_name=server)
data = monitor.query(params, server)
total, results = data['totalResultsCount'], data['results']
click.secho(f"总数据量:{total}", fg="green")
save = kw['save']
for job in results:
try:
cromwell_job = monitor.get(job['id'], server)
except Exception as e:
click.secho(f"{job['id']}\t{server}\t获取metadata失败:{e}")
continue
cromwell_job.format()
if save:
monitor.save(cromwell_job)
@cli.command()
@click.option('--show-command', '-s', is_flag=True, default=False, help="是否显示命令行内容", show_default=True)
@click.argument('prefix_or_cromwell_id')
def jobinfo(prefix_or_cromwell_id: str, show_command = False):
"""展示单个作业的执行详细信息,必须提供CromwellId或Prefix
参考YC-Cloud1展示每个task的信息
JobID JobName JobScript JobState Start Stdout Stderr Command
原理: 从cromwell获取metadata信息,解析其中的calls
"""
monitor = Monitor()
metadata = monitor.api.get_metadata(prefix_or_cromwell_id)
click.secho(f"Cromwell Metadata: {monitor.api.api}/api/v1/workflow/{metadata.get('id', '-')}/metadata", fg='green')
calls = metadata.get('calls', {})
header = ["JobID", "JobName", "JobState", "Start", "End", "Stdout", "Stderr", "Command"]
print("\t".join(header))
for taskname, items in calls.items():
# jobId, executionStatus, shardIndex,
for idx, taskitem in enumerate(items):
job = [
("jobId", taskitem.get('jobId', '-')),
("name", f"{taskname}.{idx}"),
("status", taskitem.get('executionStatus', '-')),
("start", taskitem.get('start', '-')),
("end", taskitem.get('end', '-')),
("stdout", taskitem.get('stdout', '-')),
("stderr", taskitem.get('stderr', '-')),
["command", taskitem.get('commandLine', '-')],
]
if not show_command:
job[-1][1] = '-'
line = [i[1] for i in job]
print("\t".join(line)) | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/command/monitor.py | monitor.py |
import imp
import sys
import click
from .base import AliasedGroup
# from yucebio_wdladaptor.util.config import Config
# from yucebio_wdladaptor.backend import SUPPORTTED_BACKENDS, PLACEHOLDER_SIMG_PATH, PLACEHOLDER_GLOBAL_PATH, BaseAdaptor
from yucebio.yc2.adaptor.util.api import WDLAPI
from yucebio.yc2.adaptor.util.config import Config
from yucebio.yc2.adaptor.backend import SUPPORTTED_BACKENDS, PLACEHOLDER_GLOBAL_PATH, PLACEHOLDER_SIMG_PATH
@click.group('config', cls=AliasedGroup)
def cli():
"""查看或管理Cromwell Backend配置"""
pass
@cli.command()
@click.option("--backend", "-b", type=click.Choice(list(SUPPORTTED_BACKENDS)), required=True, help="platform")
@click.option("--alias", "-a", help="Cromwell Backend别名", default=None)
@click.option('--host', '-h', help="Cromwell Backend 的 Host 地址", required=True)
@click.option('--global_path', '-g', help=f"公共文件路径,用于自动替换json中的[{PLACEHOLDER_GLOBAL_PATH}]", type=str, required=True)
@click.option('--simg_path', '-s', help=f"singulartiy镜像路径,用于自动替换json中的[{PLACEHOLDER_SIMG_PATH}]", type=str, required=True)
@click.option('--runtimes', '-r', help=f"配置当前服务支持的自定义RUNTIME属性,多个属性之间使用逗号分隔", type=str)
def add(**kw):
"""新增自定义Cromwell Backend Host。用于添加一些自定义、用于测试的Cromwell Host
{host, global_path, simg_path, backend: platform}
"""
config = Config()
if kw['runtimes']:
kw['runtimes'] = kw['runtimes'].split(',')
if kw['host']:
kw['host'] = kw['host'].strip('/')
cfg = {k: kw[k] for k in kw if kw[k]}
if not kw['alias']:
kw['alias'] = kw['backend']
config.api.add_update_backend(cfg)
@cli.command()
def ls(**kw):
"""查看预设和个人自定义的backend配置
"""
config = Config()
# 每次查询都尝试覆盖本地数据
config.init_backends()
print("\t".join(["Owner", "Alias", "Backend", "Label", "Host", "Global_Database_Path", "SIMG_Path", "Runtimes"]))
backends = config.api.get_backends()
for backend in backends:
print("\t".join([str(backend.get(k, '-')) for k in ['owner', 'alias', 'backend', 'label', 'host', 'global_path', 'simg_path', 'runtimes']]))
@cli.command()
@click.option("--alias", "-a", help="配置别名", required=True)
def delete(alias: str):
"""删除Cromwell Backend平台配置。(只能删除自定义的内容)"""
config = Config()
config.api.delete_backend(alias)
# if not alias:
# click.secho("删除出错,没有当前名称的配置项", fg='red', file=sys.stderr)
# return
# config.del_server(alias)
# config.pp(config.servers)
# if not config.api:
# return
# api = WDLAPI()
# if pre_service:
# api.delete_backend(pre_service) | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/command/cromwell.py | cromwell.py |
import sys
import click
from .base import AliasedGroup, show_error
from yucebio.yc2.adaptor.util.config import Config
@click.group('api', cls=AliasedGroup)
def cli():
"""通过适配器服务的形式管理Cromwell作业、Backend等
"""
pass
@cli.command()
# @click.option('--backend_name', '-b', help="Cromwell backend别名")
@click.option('--cromwell_id', '-j', help = "Cromwell作业编号")
@click.option('--prefix', '-p', help = "自定义分析任务编号")
@click.option('--file_type', '-t', help="指定导出类型,支持json, wdl, files, standard_data", default="json")
def export_workflow(cromwell_id, prefix, file_type):
"""导出已有作业的原始内容,如input.json
导出类型:
1. json: 导出Cromwell最终使用的JSON数据。
2. wdl: 导出Cromwell最终使用的流程定义内容
3. files: 创建一个下载分析中间结果的后台作业。
4. standard_data: 导出投递任务时使用的"标准数据格式"。
"""
if prefix and cromwell_id:
return show_error("只能使用一种编号")
if not prefix and not cromwell_id:
return show_error("至少指定一种编号")
do_action('export_workflow', {"type": file_type}, primary_value=cromwell_id if cromwell_id else prefix)
@cli.command()
@click.option('--backend_name', '-b', help="Cromwell backend别名")
@click.argument('cromwell_ids', nargs=-1)
def link_job(backend_name, cromwell_ids):
"""关联一个已存在的作业
CROMWELL_IDS: 一个或多个待关联的Crowmell作业编号
"""
api = Config().api
for cromwell_id in cromwell_ids:
try:
msg = api.submit_action('link', {"cromwell_id": cromwell_id, "backend_name": backend_name})
except Exception as e:
click.secho(f"关联失败:{cromwell_id} {e}", fg='red', file=sys.stderr)
else:
click.secho(f"关联成功: {cromwell_id} {msg}", fg="green")
def do_action(action: str, data: dict, primary_value: str = 'action', expect_response_type: str='json'):
"""基于Restful接口执行自定义操作
当primary_value=='action'时,表示操作的是整个资源
"""
c = Config()
api = c.api
try:
msg = api.submit_action(action, data, primary_value=primary_value, expect_response_type=expect_response_type)
if expect_response_type != 'json':
return msg
except Exception as e:
click.secho(f"操作失败:{e}", fg='red', file=sys.stderr)
else:
click.secho(f"操作成功: {msg}", fg="green")
@cli.command()
@click.option('--backend_name', '-b', help="按别名过滤", type=str, default=None)
def list_backends(backend_name):
"""获取服务器支持的所有Cromwell Backend
按照 host backend owner alias 列出所有已存在的cromwell backends。
"""
print("\t".join(["HOST", "Backend", "Owner", "Alias"]))
api = Config().api
backends = api.get_backends(backend_name)
for backend in backends:
print("\t".join([backend.get(k, '-') for k in ['host', 'backend', 'owner', 'alias']]))
@cli.command()
@click.argument('json', nargs=-1)
def submit(**kw):
"""通过“标准数据格式”创建通用流程(适用于生产人员,由YC2自动完成数据上传工作)
JSON: 适用于V2版本的JSON文件。其中包含模板、样本、分析流程、动态监控基本信息。后台会自动上传数据
参考:http://gitlab.yucebio.com/python-packages/wdl_api/tree/bug/workflow#%E6%8E%A5%E5%8F%A3-version-2
"""
api = Config().api
for jsonfile in kw["json"]:
try:
msg = api.submit_by_standrand_data(jsonfile)
except Exception as e:
click.secho(f"任务信息上传失败:{e},请手动将作业信息上传到服务器或联系开发人员", fg='red', file=sys.stderr)
else:
click.secho(f"上传成功: {msg}", fg="green") | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/command/api.py | api.py |
import click, sys
import datetime
from .base import BaseAdaptor
from yucebio.yc2.adaptor.util.wdl_processor import _TaskItem, _WorkflowCallItem
class Adaptor(BaseAdaptor):
PLATFORM = "BCS"
COMMAND_PREFIX = "singularity exec -W /cromwell_root -B %s,/cromwell_root,/cromwell_inputs ~{simg}"
RUNTIME_RESCOURCE_KEYS = ['cpu', 'memory']
RUNTIME_RESCOURCE_KEYS2 = ['cpu', 'memory', 'rescource_type']
SUPPORTED_RUNTIME_ATTRIBUTES = RUNTIME_RESCOURCE_KEYS + ['maxRetries', 'systemDisk', 'cluster', 'mounts', 'vpc', 'continueOnReturnCode', 'failOnStderr', 'timeout', 'autoReleaseJob', 'isv']
def convert(self):
"""遍历每个import,依次转换每个task
Description
1. 常规情况下,input.json无需处理,只有阿里云中涉及到动态资源时,需要添加额外的input
2. 常规情况下,workflow无需处理,只有阿里云中涉及到动态资源时,可能需要处理call.input和workflow.input
3. 大部分情况下需要对task的command做转换
原理
1. 加载json并解析
2. 加载workflow.wdl并解析
3. 遍历workflow.wdl的imports,依次处理每个task
3.1 根据workflow.calls决定是否需要移除未使用的task
3.2 阿里云根据task是否存在可变资源决定是否修改input.json和workflow
3.3 根据平台修改command
"""
# 遍历calls初始化被调用task对应关系
call_tasks = self.workflow_processor.call_tasks
# 1. 遍历每个import
for ns, import_item in self.workflow_processor.imports.items():
if ns not in call_tasks:
raise RuntimeError(f"Line #{import_item.line} 请移除未使用的导入内容 {import_item.path}")
call_task_info = call_tasks[ns]
# 2. 依次检测每个子任务,跳过无关的task
task_processor = import_item.wdl
click.secho(f"\n########## Process WDL [{task_processor.fileWdl}] ...", fg='yellow', file=sys.stderr)
for wdl_task_item in task_processor.meta_tasks:
task_name = wdl_task_item.name
if task_name not in call_task_info:
print(f"########## Task [{wdl_task_item.name}] 未参与本次分析,准备移除...", file=sys.stderr)
wdl_task_item.delete_content()
continue
print(f"########## Process Task [{task_name}] ", file=sys.stderr)
# 无论如何,先处理command
self.convert_command(wdl_task_item)
# 移除runtime里面的simg
if 'simg' in wdl_task_item.runtime:
wdl_task_item.delete_runtime('simg')
task_default_rescource = self.convert_task_rescource(wdl_task_item)
# 当任务没有可变资源字段时,无需额外处理
if not wdl_task_item.rescources:
continue
# 存在可变资源字段,需要进一步处理call、workflow_input
# 5. 继续向上到call中,更新里面的资源字段,可能存在多个call
call_item: _WorkflowCallItem
for call_item in call_task_info[task_name]:
# 获取当前call所提供的资源,以及来源于workflow_input中的资源变量
self.convert_call_input(call_item, wdl_task_item, task_default_rescource)
# print("in bcs end:", id(self), task_processor.fileWdl, id(task_processor))
def cluster(self, cpu: int=None, memory: int=None, rescource_type: str='Spot'):
"""根据cpu和mem参数生成可用的cluster
参考: https://batchcompute.console.aliyun.com/cn-zhangjiakou/quotas
Args:
cpu (int): cpu配置
memory (int): 内存配置, nG
"""
rescource_type = str(rescource_type).strip('\'"').lower()
# 确保名词书写正确
if rescource_type not in ['ondemand', 'spot']:
raise RuntimeError("阿里云资源类型必须填写为 OnDemand 或 Spot")
rescource_type = 'OnDemand' if rescource_type != 'spot' else 'Spot'
image_id = "img-dovfustcp606ko1kpqq000"
available_bcs_rescource = self.config("available_bcs_rescource")
if not available_bcs_rescource or not available_bcs_rescource.get("updated_at"):
raise RuntimeError("阿里云可用实例类型无效,请执行 yc2_wdl adaptor update-bcs-instance -i ACCESS_ID_KEY -s ACCESS_ID_SECRECT 来获取最新实例配置")
last_update_at = datetime.datetime.fromisoformat(available_bcs_rescource["updated_at"])
if (datetime.datetime.today() - last_update_at).days > 7:
click.secho("WARNING: 距离上次更新阿里云可用实例类型已经超过7天,为避免实例变更导致任务无法执行,请执行 yc2_wdl adaptor update-bcs-instance -i ACCESS_ID_KEY -s ACCESS_ID_SECRECT 来获取最新实例配置", fg="yellow")
raise RuntimeError("阿里云可用实例类型配置可能已过期,请执行 yc2_wdl adaptor update-bcs-instance -i ACCESS_ID_KEY -s ACCESS_ID_SECRECT 来获取最新实例配置")
expected_key = "AvailableSpotInstanceType" if rescource_type == 'Spot' else "AvailableClusterInstanceType"
cpu2mem = {}
for instance_config in available_bcs_rescource[expected_key]:
# dict_keys(['CpuCore', 'InstanceType', 'MemorySize', 'Network'])
_cpu, _mem, instance_type = instance_config['CpuCore'], instance_config['MemorySize'], instance_config['InstanceType']
if _cpu not in cpu2mem:
cpu2mem[_cpu] = {}
if _mem not in cpu2mem[_cpu]:
cpu2mem[_cpu][_mem] = []
cpu2mem[_cpu][_mem].append(instance_type)
if not cpu:
cpu = 2
if not memory:
memory = 4
for c in sorted(cpu2mem.keys()):
if c < cpu:
continue
m2ins = cpu2mem[c]
for m in sorted(m2ins.keys()):
if m < memory:
continue
# print(f">>>>>>> CPU({cpu} => {c}) MEM({memory} => {m}) {m2ins[m][0]} <<<<<<<<<")
return f"{rescource_type} {m2ins[m][0]} {image_id}"
raise RuntimeError(f"无法找到满足最低需求[cpu: {cpu}, mem: {memory}]的阿里云实例类型")
def convert_command(self, ti: _TaskItem):
tab = ' ' * ti.processor.tab_size
command_prefix = self.COMMAND_PREFIX % self.bind_path
new_command_contents = "\n".join([
# f"{tab}{tab}set -e\n", # 不要捕获singularity的错误
f"{tab}{tab}{command_prefix} bash -s <<'ENDOFCMD'",
*[f"{tab}{tab}{tab}{line}" for line in ti.command_content_lines],
f"{tab}{tab}ENDOFCMD",
# 读取、打印并返回状态码
f"{tab}{tab}status=$? && echo \"singularity exec status: $?\" && exit $status",
])
ti.update_command(new_command_contents)
def convert_task_rescource(self, wdl_task_item: _TaskItem):
"""处理task中的可变资源,返回该task中计算出的资源默认值
Args:
wdl_task_item (_TaskItem): 。。。
"""
# 无论如何都要先转换下runtime的资源字段
runtime_default_data = self.convert_runtime(wdl_task_item)
if not bool(wdl_task_item.rescources):
return {}
# 需要转换task_input
return self.convert_task_input(wdl_task_item, runtime_default_data)
def convert_runtime(self, wdl_task_item: _TaskItem):
"""转换runtime中的资源值,返回常量资源的默认值
Args:
wdl_task_item (_TaskItem): ...
"""
runtime_resouce_data, runtime_default_data, input_rescource_keys = {}, {}, []
for k in wdl_task_item.RUNTIME_RESCOURCE_KEYS:
if k not in wdl_task_item.runtime:
continue
v = wdl_task_item.runtime[k]
runtime_resouce_data[k] = v
if v in wdl_task_item.inputs:
input_rescource_keys.append([k, v])
else:
if k != 'rescource_type':
try:
v = int(v)
except Exception:
raise RuntimeError(f"[{wdl_task_item.processor.fileWdl}@{wdl_task_item.name}] RUNTIME属性[{k}]不是整数或者未找到对应的input变量")
runtime_default_data[k] = v
# 移除runtime中的资源字段
wdl_task_item.delete_runtime(k)
if not input_rescource_keys:
default_cluster = self.cluster(**runtime_default_data)
# print(f"{wdl_task_item.processor.fileWdl}@{wdl_task_item.name} 无可变资源,设置cluster为 '{default_cluster}', 资源量{runtime_default_data}")
wdl_task_item.update_runtime('cluster', f'"{default_cluster}"')
else:
wdl_task_item.update_runtime('cluster', "cluster")
self.filter_or_append_runtime_attributes(wdl_task_item)
return runtime_default_data
def convert_task_input(self, wdl_task_item: _TaskItem, runtime_default_data: dict={}):
"""转换task的input中的资源值,只能新增字段,需要校验字段被占用的情况
Args:
wdl_task_item (_TaskItem): ...
"""
input_default_data, shouldCalcCluster = {}, True
for input_rescource_key, input_rescource_item in wdl_task_item.rescources.items():
if input_rescource_item.get('default'):
# 解析过程中已经确保资源字段默认值是数值了
input_default_data[input_rescource_item['runtime']] = input_rescource_item['default']
else:
# 当且仅当input中所有资源字段都有默认值时,需要在input中设置cluster的默认值
shouldCalcCluster = False
task_default_rescource = {**runtime_default_data, **input_default_data}
# # 当input中所有资源字段都有默认值时,需要在input中设置cluster的默认值
default_cluster = None
if shouldCalcCluster:
# click.secho(f"input中的所有资源字段都有默认值,需要计算cluster, {input_default_data}", fg='green')
default_cluster = '"%s"' % self.cluster(**task_default_rescource)
wdl_task_item.update_input('cluster', 'String', default = default_cluster)
return task_default_rescource
def convert_call_input(self, call_item: _WorkflowCallItem, wdl_task_item: _TaskItem, task_default_rescource: dict = {}):
"""更新指定call的input。 返回需要提供给该call的资源变量及其来源。 @2021年3月25日 call中不允许设置资源变量
Args:
call_item (_WorkflowCallItem): ...
wdl_task_item (_TaskItem): ...
task_default_rescource (dict, optional): .... Defaults to {}.
Description
1. call中指定了task_input中的所有资源变量的默认值 ==> 可以处理:直接在call中处理
2. call中未指定任何可变资源 ==> 可以处理:直接到json中处理
3. 其他情况 ==> 无法处理
3.1 task存在cpu和mem两种可变资源,call中指定了cpu的默认值,json中指定了mem的默认值
call: 保留cpu默认值,增加cluster变量
json: 保留mem默认值,增加cluster,设置默认值
3.2 task存在cpu变量,call中将cpu指向workflow.input的变量,workflow.input中设置了默认值
call: 保留cpu默认值,增加cluster变量
workflow.input: 保留mem默认值,增加cluster,设置默认值
3.3 task存在cpu变量,call中将cpu指向workflow.input的变量,workflow.input中引用了json的值
call: 保留变量,增加cluster:cluster_{call_alias}
workflow.input: 保留原变量,增加变量cluster_{call_alias}
json: 增加workflow级别字段 cluster_{call_alias}并计算默认值
特殊场景:
task里面有cpu和mem,其中mem有默认值
call中设置了cpu的默认值,没有mem
此时: input.json里面可能设置了mem值,也可能没有
"""
# 记录该call依赖的json级别的输入:task中声明了资源字段,call中未指定该字段时,需要有json中对应的call_alias提供
# 特别的,若json级别的依赖在task里面有默认值,此时json级别该参数就变成可选参数了,此时需要根据json中是否提供该数据来决定call中使用变量还是常量的cluster
required_json_inputs = []
# 记录该call依赖的workflow级别的输入:task中声明了资源字段,call中设置了对应字段,但不是常量值,此时数据需要有workflow.input提供
# 特别的,若该依赖在task里有默认值,则无论如何,该默认值需要被屏蔽
required_workflow_inputs = []
# 获取并记录json中提供的当前call对应的所有字段以及资源字段
json_task_inputs, json_task_rescouce_data = self.input_processor.call_input(call_item.alias), {}
# 获取并记录json中提供的workflow级别的字段以及其中的资源字段
json_workflow_inputs, json_workflow_rescource_data = self.input_processor.inputs, {}
workflow_inputs, workflow_defalut_rescource_data = self.workflow_processor.inputs, {}
# 记录当且call设置的资源字段以及值,若值时常量,记录下默认值
rescource_data, default_data = {}, {}
# 检测call.input中是否存在资源变量,若存在则直接报错
for rescource_key, task_rescource_item in wdl_task_item.rescources.items():
# 当前资源值在runtime中的key: cpu或mem或rescource_type
runtime_key = task_rescource_item['runtime']
if rescource_key not in call_item.inputs:
required_json_inputs.append(rescource_key)
# 只要这个字段出现在json中,就不要在call计算cluster
if rescource_key in json_task_inputs:
json_task_rescouce_data[runtime_key] = json_task_inputs[rescource_key]
else:
# 这个值一定要有默认值
if runtime_key not in task_default_rescource:
raise RuntimeError(f"需要配置{self.workflow_processor.workflow_name}.{call_item.alias}.{rescource_key}")
continue
# raise RuntimeError(f"文件:{self.workflow_processor.fileWdl}不允许在流程的Call[{call_item.alias}]中设置资源变量[{rescource_key}]")
rescource_data[rescource_key] = call_item.inputs[rescource_key]
# 检测input中的值是常量还是变量: 如果是变量,它一定是workflow.inputs中的变量
if rescource_data[rescource_key] in workflow_inputs:
# 需要记录workflow.input中的资源字段与runtime中的字段对应关系
workflow_rescource_key = rescource_data[rescource_key]
required_workflow_inputs.append([workflow_rescource_key, runtime_key])
if workflow_rescource_key in json_workflow_inputs:
# 资源值最终从json提取
# cpu和mem需要转换为整数
if runtime_key != 'rescouce_type':
try:
json_workflow_rescource_data[runtime_key] = int(json_workflow_inputs[workflow_rescource_key])
except Exception:
raise RuntimeError(f"字段{self.workflow_processor.workflow_name}.{workflow_rescource_key}无法转换为整数")
else:
# 资源值有默认值
workflow_input_item = workflow_inputs[workflow_rescource_key]
# 校验:必须提供默认值
if not workflow_input_item.get('default'):
raise RuntimeError(f"{self.workflow_processor.fileWdl}@{self.workflow_processor.workflow_name} 未配置INPUT中参数[{workflow_rescource_key}]的值")
# TODO: 需要校验默认值格式!
workflow_defalut_rescource_data[runtime_key] = workflow_input_item['default']
# raise RuntimeError(f"[{self.workflow_processor.fileWdl}@{self.workflow_processor.workflow_name}]流程的CALL[{call_item.alias}]中的资源变量[{rescource_key}]只能设置常量")
continue
try:
default_data[runtime_key] = int(rescource_data[rescource_key]) if runtime_key != 'rescouce_type' else rescource_data[rescource_key]
except Exception:
raise RuntimeError(f"{self.workflow_processor.fileWdl}@{self.workflow_processor.workflow_name} CALL[{call_item.alias}] input中的资源字段[{rescource_key}]的默认值必须是整数")
# 1. call中未定义资源字段,即所有资源字段都依赖于json。此时只需要在input的当前call中增加cluster,并根据json中的数据和task中的数据计算出实际值
if not rescource_data:
# print("需要在json中配置资源值", required_json_inputs)
# 根据当前call对应的json中的资源值,计算出cluster,添加到input中
args = {**task_default_rescource, **json_task_rescouce_data}
cluster = self.cluster(**args)
self.input_processor.update_task_input(call_item.alias, 'cluster', cluster)
return []
# 存在资源字段
# 2 资源字段都有默认值
if not required_workflow_inputs and not required_json_inputs:
# 此时只需要在call.input中增加cluster,并根据call的资源数据和task中的默认值计算出实际值
# print("直接使用call中的数据计算出cluster", rescource_data, default_data)
args = {**task_default_rescource, **json_task_rescouce_data}
cluster = self.cluster(**args)
# TODO: 支持修改call的input属性
# call_item.up
raise RuntimeError(f"{self.workflow_processor.fileWdl}@{self.workflow_processor.workflow_name} CALL[{call_item.alias}] 暂时不支持修改input值")
return []
# 需要额外的来源: 如cpu来源于json, mem来源于workflow.input
# 3 仅需要json来源:call中不需要增加变量,json中增加cluster变量,根据call默认值+task默认值+json数据计算出实际值
if not required_workflow_inputs:
# print("call中有默认值,同时依赖json数据", rescource_data, default_data, task_default_rescource, json_task_rescouce_data)
args = {**task_default_rescource, **default_data, **json_task_rescouce_data}
cluster = self.cluster(**args)
self.input_processor.update_task_input(call_item.alias, 'cluster', cluster)
return []
# 4 仅需要workflow.input: 此时需要根据task默认值+call默认值+workflow默认值+json_workflwo数据计算cluster
if not required_json_inputs:
# 4.1 若仅需要workflow默认值:在workflow中增加cluster, call中同样增加cluster
if not json_workflow_rescource_data:
# print("从workflow.input中提取资源值")
# TODO: call中增加自定义input, workflow.input中增加自定义input
raise RuntimeError(f"{self.workflow_processor.fileWdl}@{self.workflow_processor.workflow_name} 不支持自动修改call和workflow的input内容")
# auto_add_cluster_key = f"cluster_{call_item.alias}"
# # call_item.add_input('cluster', auto_add_cluster_key)
# args = {**task_default_rescource, **default_data, **workflow_defalut_rescource_data}
# cluster = self.cluster(**args)
# self.workflow_processor.add_input(auto_add_cluster_key, 'String', f'"{cluster}"')
# 4.2 workflow中的资源值同时来源于json中:此时直接根据各种数据计算出task的cluster值统一为task的cluster输入写入json中
else:
# print("资源值来源于workflow以及json")
args = {**task_default_rescource, **default_data, **workflow_defalut_rescource_data, **json_workflow_rescource_data}
cluster = self.cluster(**args)
self.input_processor.update_task_input(call_item.alias, 'cluster', cluster)
return []
# 3.3 全都需要
raise RuntimeError(f"{self.workflow_processor.fileWdl}@{self.workflow_processor.workflow_name} 可变资源来源过于复杂,暂不支持") | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/backend/bcs.py | bcs.py |
import io
import sys
import json
import os
from typing import Any
import zipfile
from importlib_metadata import pathlib
import requests
from yucebio.yc2.adaptor.util.config import Config
from yucebio.yc2.adaptor.util.input_processor import InputProcessor
from yucebio.yc2.adaptor.util.wdl_processor import WorkflowProcess, _TaskItem
from .types import BackendConfigType
PLACEHOLDER_GLOBAL_PATH = '__GLOBAL__'
PLACEHOLDER_SIMG_PATH = '__SIMG__'
class BaseAdaptor(object):
wdl_version = 1.0
PLATFORM = "default"
HOST = "http://127.0.0.1:8000"
COMMAND_PREFIX = "singularity exec -W /cromwell_root -B %s,/cromwell_root,/cromwell_inputs ~{simg}"
SUPPORTED_RUNTIME_ATTRIBUTES = ['cpu', 'memory', 'maxRetries']
def __init__(self, backend_config: BackendConfigType = None) -> None:
self.backend_config = backend_config
self.input_processor = None
self.workflow_processor = None
# 存放每个import的task信息
self.meta = {}
self._config = Config()
# 用于支持添加全局runtime属性
self.global_runtimes = {}
@property
def supported_runtime_attributes(self):
return (self.backend_config.get('runtimes') or []) + (self.SUPPORTED_RUNTIME_ATTRIBUTES or [])
def config(self, key: str = None) -> dict:
"""查询或更新配置: cromwell api地址, 公共目录以及simg目录必须配置
1. 查询 c = adaptor.config()
2. 查询指定配置 c = adaptor.config('aws')
"""
if key:
return self._config.get(key, {})
return self._config.config
@property
def global_path(self):
return self.backend_config.get('global_path')
@property
def simg_path(self):
return self.backend_config.get('simg_path')
@property
def bind_path(self):
"""将command放到singularity中执行时,需要指定映射的目录"""
return self.global_path + ',' + self.simg_path
def parse_input(self, input_path: str = None):
if isinstance(input_path, InputProcessor):
self._input_file = input_path.filepath
self.input_processor = input_path
return
if input_path:
self._input_file = input_path
self.input_processor = InputProcessor(self._input_file)
def parse_workflow(self, wdl_path: str = None, package_path: str = None):
if wdl_path:
self._wdl_path = wdl_path
self.workflow_processor = WorkflowProcess(self._wdl_path, package_path=package_path)
def parse(self, wdl_path: str=None, input_path: str=None, **kw):
self.parse_input(input_path)
self.parse_workflow(wdl_path, package_path=kw.get('package_path'))
if not self.global_path:
raise RuntimeError(f"请配置当前平台[{self.PLATFORM.lower()}(别名{self.config_alias})]的公共目录路径[global_path]")
# @2021年8月20日 支持添加静态自定义runtime属性
if kw.get('runtimes'):
# 获取用户提供的需要自动添加的runtime属性
runtime_keys = kw["runtimes"].split(',')
# 从input_json中提取自动添加的runtime属性值
inputs = self.input_processor.inputs
for k in runtime_keys:
if k not in inputs:
raise RuntimeError(f"请在{self.input_processor.filepath}中提供[{self.input_processor.workflow_name}.{k}]初始值")
self.global_runtimes[k] = inputs[k]
def convert(self):
"""遍历每个import,依次转换每个task
Description
1. 常规情况下,input.json无需处理,只有阿里云中涉及到动态资源时,需要添加额外的input
2. 常规情况下,workflow无需处理,只有阿里云中涉及到动态资源时,可能需要处理call.input和workflow.input
3. 大部分情况下需要对task的command做转换
原理
1. 加载json并解析
2. 加载workflow.wdl并解析
3. 遍历workflow.wdl的imports,依次处理每个task
3.1 根据workflow.calls决定是否需要移除未使用的task
3.2 阿里云根据task是否存在可变资源决定是否修改input.json和workflow
3.3 根据平台修改command
"""
raise NotImplementedError("method 'convert' should implemented by sub class")
def filter_or_append_runtime_attributes(self, ti: _TaskItem):
"""移除不支持的runtime属性、并添加默认runtime属性
"""
# 移除不支持的RUNTIME属性
if self.supported_runtime_attributes:
for k in dict(ti.runtime):
if k not in self.supported_runtime_attributes:
print("DELETE NOT SUPPORTED RUNTIME ATTRIBUTE:", k, file=sys.stderr)
ti.delete_runtime(k)
# 添加默认runtime属性
if not self.global_runtimes:
return
for k,v in self.global_runtimes.items():
ti.update_runtime(k, repr(v))
self.filter_unused_input_attributes(ti)
def filter_unused_input_attributes(self, ti: _TaskItem):
"""@TODO: 2021-09-07 检查task的input参数与input.json中的参数是否一致
"""
pass
def pp(self, obj: Any):
print(json.dumps(obj, indent=2, default=str))
@property
def stream_workflow(self) -> io.BytesIO:
return io.BytesIO(str(self.workflow_processor).encode('utf8'))
@property
def stream_input(self) -> io.BytesIO:
context = str(self.input_processor)
if PLACEHOLDER_GLOBAL_PATH in context:
global_path = self.global_path
if not global_path:
raise RuntimeError(f"请配置global_path参数")
context = context.replace(PLACEHOLDER_GLOBAL_PATH, global_path)
if PLACEHOLDER_SIMG_PATH in context:
simg_path = self.simg_path
if not simg_path:
raise RuntimeError(f"请配置simg_path参数")
context = context.replace(PLACEHOLDER_SIMG_PATH, simg_path)
return io.BytesIO(context.encode('utf8'))
@property
def stream_bundle(self) -> io.BytesIO:
if not self.workflow_processor.imports:
return None
in_memory_file = io.BytesIO()
z = zipfile.ZipFile(in_memory_file, 'a')
for import_item in self.workflow_processor.imports.values():
wdl = import_item.wdl
# 打包导入文件到tar中
dirname = os.path.dirname(import_item.path) + '/'
if dirname not in z.namelist():
# print('add path', dirname)
zipinfo_dir = zipfile.ZipInfo(dirname)
zipinfo_dir.compress_type = zipfile.ZIP_STORED
zipinfo_dir.external_attr = 0o40755 << 16 # permissions drwxr-xr-x
zipinfo_dir.external_attr |= 0x10 # MS-DOS directory flag
z.writestr(zipinfo_dir, '')
zipinfo = zipfile.ZipInfo(import_item.path)
zipinfo.external_attr = 0o644 << 16 # permissions -r-wr--r--
# click.secho(f"in base zip_import_file: path[{wdl.fileWdl}] id[{id(wdl)}]", fg='green')
z.writestr(zipinfo, str(wdl))
z.close()
in_memory_file.seek(0)
return in_memory_file
def generate_file(self, outdir = './'):
"""生成适配后的输出文件
"""
cfg = self.backend_config
# 任务投递shell:
restful_content = [
'curl -X POST "{host}/api/workflows/v1"',
'-H "accept: application/json" -H "Content-Type: multipart/form-data"',
'-F "workflowSource=@{wdl}"',
'-F "workflowInputs=@{input_json};type=application/json"'
]
host = cfg.get('host', self.HOST)
platform = "default" if not self.PLATFORM else self.PLATFORM
output_path = pathlib.Path(outdir)/platform.lower()
output_path.mkdir(parents=True, exist_ok=True)
# bundle = "bundle." + platform + ".tar"
bundle_file = self.zip_import_file(path=output_path)
if bundle_file:
restful_content.append('-F "workflowDependencies=@{bundle};type=application/x-zip-compressed"')
# wdl = '/'.join([output_path, os.path.basename(self.workflow_processor.fileWdl)])
wdl = output_path/os.path.basename(self.workflow_processor.fileWdl)
with open(wdl, 'w', encoding='utf8') as w:
w.write(str(self.workflow_processor))
# input_json = '.'.join([os.path.splitext(self.input_processor.filepath)[0], platform, 'json'])
input_json = output_path/(os.path.splitext(os.path.basename(self.input_processor.filepath))[0] + ".json")
# input_json = '/'.join([
# output_path,
# os.path.splitext(os.path.basename(self.input_processor.filepath))[0] + ".json"
# ])
with open(input_json, 'w', encoding='utf8') as w:
context = str(self.input_processor)
if PLACEHOLDER_GLOBAL_PATH in context:
global_path = self.global_path
if not global_path:
raise RuntimeError(f"请配置global_path参数")
context = context.replace(PLACEHOLDER_GLOBAL_PATH, global_path)
if PLACEHOLDER_SIMG_PATH in context:
simg_path = self.simg_path
if not simg_path:
raise RuntimeError(f"请配置simg_path参数")
context = context.replace(PLACEHOLDER_SIMG_PATH, simg_path)
w.write(context)
print("\n", (' \\\n\t'.join(restful_content)).format(
host=host, wdl=wdl, input_json=input_json, bundle=bundle_file
)
)
def zip_import_file(self, existsZip=None, path="./"):
"""打包导入文件
"""
# 遍历import: 只有workflow中有import, task里面没有也不应该有import
if not self.workflow_processor.imports:
return None
platform = "default" if not self.PLATFORM else self.PLATFORM
filename = pathlib.Path(path)/f"bundle.zip"
z: zipfile.ZipFile = existsZip
if not z:
if os.path.exists(filename):
os.remove(filename)
z = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)
for import_item in self.workflow_processor.imports.values():
wdl = import_item.wdl
# 打包导入文件到tar中
dirname = os.path.dirname(import_item.path) + '/'
if dirname not in z.namelist():
# print('add path', dirname)
zipinfo_dir = zipfile.ZipInfo(dirname)
zipinfo_dir.compress_type = zipfile.ZIP_STORED
zipinfo_dir.external_attr = 0o40755 << 16 # permissions drwxr-xr-x
zipinfo_dir.external_attr |= 0x10 # MS-DOS directory flag
z.writestr(zipinfo_dir, '')
zipinfo = zipfile.ZipInfo(import_item.path)
zipinfo.external_attr = 0o644 << 16 # permissions -r-wr--r--
# click.secho(f"in base zip_import_file: path[{wdl.fileWdl}] id[{id(wdl)}]", fg='green')
z.writestr(zipinfo, str(wdl))
# print(str(wdl))
if not existsZip:
z.close()
return filename
def submit(self):
host = self.backend_config['host']
wdl = os.path.basename(self.workflow_processor.fileWdl)
input_json = os.path.splitext(os.path.basename(self.input_processor.filepath))[0] + ".json"
files = {
"workflowSource": (wdl, self.stream_workflow),
"workflowInputs": (input_json, self.stream_input),
"workflowDependencies": ("bundle.zip", self.stream_bundle)
}
rsp = requests.post(f"{host}/api/workflows/v1", files=files)
rsp_data = rsp.json()
return rsp_data['id']
def metadata(self, cromwell_id: str):
host = self.backend_config['host']
rsp = requests.get(f"{host}/api/workflows/v1/{cromwell_id}/metadata")
return rsp.json() | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/backend/base.py | base.py |
import click, sys
from .base import BaseAdaptor
from yucebio.yc2.adaptor.util.wdl_processor import _TaskItem, _WorkflowCallItem
class Adaptor(BaseAdaptor):
"""转换WORKFLOW到泰州SGE平台
不需要额外处理,Cromwell的SGE backend中可以支持singularity适配
"""
PLATFORM = "SGE"
SUPPORTED_RUNTIME_ATTRIBUTES = ['cpu', "mem", 'memory', 'maxRetries', "sge_queue", "sge_project", "simg", "mount", 'continueOnReturnCode', 'owner']
def convert(self):
# 遍历calls初始化被调用task对应关系
call_tasks = self.workflow_processor.call_tasks
# 1. 遍历每个import
for ns, import_item in self.workflow_processor.imports.items():
if ns not in call_tasks:
raise RuntimeError(f"Line #{import_item.line} 请移除未使用的导入内容 {import_item.path}")
call_task_info = call_tasks[ns]
# 2. 依次检测每个子任务,跳过无关的task
task_processor = import_item.wdl
click.secho(f"\n########## Process WDL [{task_processor.fileWdl}] ...", fg='yellow', file=sys.stderr)
for wdl_task_item in task_processor.meta_tasks:
task_name = wdl_task_item.name
if task_name not in call_task_info:
print(f"########## Task [{wdl_task_item.name}] 未参与本次分析,准备移除...", file=sys.stderr)
wdl_task_item.delete_content()
continue
print(f"########## Process Task [{task_name}] ", file=sys.stderr)
# SGE 平台只需要过滤掉不支持的RUNTIME属性
self.filter_or_append_runtime_attributes(wdl_task_item)
# 将runtime中的 memory 转换成字符串
runtime_mem = wdl_task_item.runtime.get('memory')
if not runtime_mem:
continue
# 3.1 runtime.memory是固定值,直接转换
if runtime_mem not in wdl_task_item.inputs:
wdl_task_item.update_runtime("memory", f'"{runtime_mem} GB"')
continue
# 3.2. runtime.memory是变量
else:
wdl_task_item.update_runtime("memory", '"~{' + runtime_mem +'} GB"')
wdl_task_item.update_runtime("maxRetries", 3) | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/backend/sge.py | sge.py |
from .base import BaseAdaptor
from yucebio.yc2.adaptor.util.wdl_processor import _TaskItem
import click
class Adaptor(BaseAdaptor):
"""转换WORKFLOW到亚马逊平台
1. input:
必须提供simg, 类型必须是String
2. command
需要将命令包裹到singularity内
3. runtime
设置固定的docker和disks, memory设置为带单位的字符串
"""
PLATFORM = "AWS"
COMMAND_PREFIX = "singularity exec -W /cromwell_root -B %s,/cromwell_root ~{simg}"
SUPPORTED_RUNTIME_ATTRIBUTES = ['cpu', 'memory', 'disks', 'docker', 'continueOnReturnCode']
def convert(self):
call_tasks = self.workflow_processor.call_tasks
for ns, import_item in self.workflow_processor.imports.items():
call_task_info = call_tasks[ns]
# 2. 依次检测每个子任务,跳过无关的task
task_processor = import_item.wdl
click.secho(f"\n########## Process WDL [{task_processor.fileWdl}] ...", fg='yellow')
for wdl_task_item in task_processor.meta_tasks:
task_name = wdl_task_item.name
if task_name not in call_task_info:
print(f"########## Task [{wdl_task_item.name}] 未参与本次分析,准备移除...")
wdl_task_item.delete_content()
continue
print(f"########## Process Task [{task_name}] ")
# 无论如何,先处理command
self.convert_command(wdl_task_item)
# 移除runtime里面的simg
if 'simg' in wdl_task_item.runtime:
wdl_task_item.delete_runtime('simg')
# 检测各种资源值,将cpu和mem转换为字符串值
self.convert_runtime(wdl_task_item)
def convert_command(self, ti: _TaskItem):
tab = ' ' * ti.processor.tab_size
command_prefix = self.COMMAND_PREFIX % self.bind_path
new_command_contents = "\n".join([
f"{tab}{tab}{command_prefix} bash -s <<'ENDOFCMD'",
*[f"{tab}{tab}{tab}{line}" for line in ti.command_content_lines],
f"{tab}{tab}ENDOFCMD"
])
ti.update_command(new_command_contents)
def convert_runtime(self, ti: _TaskItem):
"""检测cpu和memory是否为常量,若为常量,将它修改为字符串,若为变量,需要在后面拼接一个"G"
docker, disks, cpu, memory
亚马逊通过queueArn管理实例,作业集群默认设置了竞价或按需模式
"""
# 1. 增加docker
if 'docker' in ti.runtime and ti.runtime['docker'].strip("\"'") != "kongdeju/singularity:2.6.1":
raise RuntimeError(f"{ti.processor.fileWdl}@{ti.name} 不允许自定义docker")
# runtime_kvs['docker'] = 'docker: "kongdeju/singularity:2.6.1"'
ti.update_runtime("docker", '"kongdeju/singularity:2.6.1"')
# 2. 配置disk
ti.update_runtime("disks", '"/efs 100 SSD"')
if 'memory' not in ti.runtime:
return
# 3. memory修改为带单位的字符串
input_key_mem = ti.runtime['memory']
# 若runtime中有默认值:修改为字符串
if input_key_mem not in ti.inputs:
ti.update_runtime("memory", f'"{input_key_mem}G"')
else:
ti.update_runtime("memory", f'{input_key_mem} + "G"')
# 移除不支持的RUNTIME属性
self.filter_or_append_runtime_attributes(ti) | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/backend/aws.py | aws.py |
from typing import Any
import os
import json5
DEFAULT_CONFIG_DIR = ".yucebioconfig"
DEFAULT_USER_CONFIG_DIR = 'config'
class Config(object):
def __init__(self, name: str = None, path: str = None):
"""固定使用 ~/.yucebioconfig/{name}.json5
Args:
name (str, optional): 配置名称. Defaults to None.
path (str, optional): 配置所在路径,若未指定,则固定使用~. Defaults to None.
"""
self.configpath = self.detect_config_path(path or DEFAULT_CONFIG_DIR)
self.name = name or DEFAULT_USER_CONFIG_DIR
self.configfile = os.path.join(self.configpath, self.name + '.json5')
self._config = self.load()
def detect_config_path(self, path_name: str):
path_in_cwd = os.path.join(os.curdir, path_name)
if os.path.exists(path_in_cwd):
return path_in_cwd
return os.path.join(os.path.expanduser('~'), path_name)
@property
def config(self) -> dict:
return self._config
# 初始化
def load(self):
if not os.path.exists(self.configfile):
return {}
with open(self.configfile, encoding='utf8') as r:
self._config: dict= json5.load(r)
return self._config
# 保存配置
def save(self):
if not os.path.exists(self.configpath):
os.makedirs(self.configpath)
with open(self.configfile, 'w') as w:
json5.dump(self._config, w, indent=2)
# 重新加载配置
def reload(self):
self.save()
self._config = self.load()
# 更新配置
def update(self, data: dict):
self._config.update(data)
self.save()
def clear(self, key: str=None, sep: str=None):
"""清除指定key对应的配置项,嵌套字段使用sep分隔。如 clear('a.b', sep='.')会清除字段a的子字段b的配置项
Args:
key (str, optional): 待清除的key. Defaults to None.
sep (str, optional): 自定义嵌套字段分隔符. Defaults to None.
"""
if not key:
self._config = {}
else:
keys = [key] if not sep else key.split(sep)
_ref, final_key = self._config, keys[-1]
for k in keys[:-1]:
if k not in _ref:
return
_ref = _ref[k]
if final_key in _ref:
del _ref[final_key]
self.save()
def __getitem__(self, key: str, default=None) -> Any:
return self.config.get(key, default)
def __contains__(self, key: str) -> bool:
return key in self.config
def __setitem__(self, key: str, value: Any):
self.config[key] = value
def __call__(self, key: str, value: Any = None) -> Any:
return self._config.get(key, value)
config = Config()
if __name__ == '__main__':
print(config) | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/base_config.py | base_config.py |
import datetime
import os
import sys, requests
import typing
import jwt
from . import types
from .base_config import Config as BaseConfig
from .ldap import LDAP
from .api import WDLAPI
DEFAULT_PATH = '.yucebioconfig_v2'
class Config(BaseConfig):
def __init__(self, name: str = 'wdladaptor', path: str = DEFAULT_PATH, check_user: bool = True):
super().__init__(name=name, path=path)
self.load()
# print(self._config)
if check_user:
self.check_user()
@property
def backends(self) -> typing.List[types.CromwellBackendType]:
"""获取所有可用backend
"""
backends = self.get('backends')
if not backends:
backends = self.init_backends()
# 检查本地数据是否过期: 每天更新一次
try:
update_at = datetime.date.fromisoformat(backends['update_at'])
if update_at < datetime.date.today() + datetime.timedelta(-1):
backends = self.init_backends()
except:
pass
return backends['data']
@property
def api(self):
"""获取YC-Clou2 API服务器实例
"""
return WDLAPI(self.get('api', 'http://yc2.yucebio.com'), self.get('owner'))
def owner(self):
"""获取当前操作人"""
return self.get('owner', '')
def set(self, key: str, value):
self._config[key] = value
self.reload()
def get(self, key: str, default = None):
return self.config.get(key, default)
def init_backends(self):
"""从API获取数据保存到本地"""
try:
backends = self.api.get_backends()
except:
return
saved_backends = {"update_at": datetime.date.today().isoformat(), "data": backends}
self.set('backends', saved_backends)
return saved_backends
def set_api(self, api: str):
rsp = requests.get(api)
self.set('api', api)
return rsp.json()
def check_user(self):
"""检查用户信息
1. 检查token是否有效,若token有效,则以token为准
2. 检查当前登录人是否为ldap有效用户,若是,则自动登录,并更新token
3. 报错,要求用户登录
"""
# 1. 检查配置文件中的token是否有效
user_info = self.check_token()
if not user_info:
# 若token无效,基于ldap检查登录用户
system_username = os.getlogin()
print("使用当前系统登录用户自动登录", system_username)
user_info = LDAP().get_user(system_username)
if not user_info:
raise RuntimeError("需要登录")
# # 更新过期时间
user_info = {
"name": user_info['name'],
"exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=7)
}
self.set('token', jwt_encode(user_info))
if self.get('owner') != user_info['name']:
self.set('owner', user_info['name'])
self.reload()
return user_info
def login(self, username: str, password: str):
"""基于LDAP实现登录"""
LDAP().check_login(username, password)
payload = {
"name": username,
# 7天内免登录
"exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=7)
}
token = jwt_encode(payload)
self.set('token', token)
self.reload()
print(jwt_decode(token))
return True
def check_token(self) -> types.UserType:
"""解析jwt-token,提取用户信息
Args:
token (str): jwt token
"""
if not self.get('token'):
return {}
try:
# jwt自带过期时间校验功能
return jwt_decode(self.get('token'))
except:
return {}
def get_backend_config(self, backend_alias: str):
"""在预设和自定义backend中找到最匹配的
"""
backends = self.backends
if not backends:
raise RuntimeError("无法获取Cromwell backends信息")
candidate_config = []
for backend in backends:
if backend["alias"] == backend_alias:
if backend["owner"] == self.owner:
return backend
candidate_config.append(backend)
if not candidate_config:
raise RuntimeError(f"未找到匹配的Cromwell Backend。(alias=={backend_alias})")
return candidate_config[0]
JWT_KWY = DEFAULT_PATH
def jwt_encode(payload: dict, algorithm: str = 'HS256'):
"""基于jwt保存用户信息
Args:
payload (dict): 待保存的数据
key (str): 用于"加密"的辅助信息
Refer to https://pyjwt.readthedocs.io/en/stable/algorithms.html
"""
return jwt.encode(payload=payload, key=JWT_KWY, algorithm=algorithm)
def jwt_decode(token: str, algorithm: str = 'HS256'):
return jwt.decode(token, key=JWT_KWY, algorithms=[algorithm]) | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/config.py | config.py |
import json5 as json
class InputProcessor(object):
"""WDL流程输入数据处理工具。支持解析、更新、格式化"""
META_NAME = "workflow_name"
META_INPUT = "input"
META_CALL = "call"
def __init__(self, filepath: str, indent=2, raw_inputs: dict = None) -> None:
self.filepath = filepath
self.indent = indent
self.meta = {
self.META_NAME: None,
self.META_INPUT: {},
self.META_CALL: {}
}
self.raw_inputs = raw_inputs
if not raw_inputs:
with open(self.filepath) as r:
self.raw_inputs: dict = json.load(r)
self._parse()
def _parse(self):
input_maps = {}
for key, value in self.raw_inputs.items():
sub = key.split('.')
tmp = input_maps
for k in sub[:-1]:
if k not in tmp:
tmp[k] = {}
tmp = tmp[k]
tmp[sub[-1]] = value
# 1. 顶层必须只能有一个名字: 只能有一个workflow
top_levels = list(input_maps.keys())
if len(top_levels) != 1:
raise RuntimeError(f"输入数据中WORKFLOW名称不一致,{top_levels}")
self.meta[self.META_NAME] = top_levels[0]
# 解析call和inputs
for key, value in input_maps[top_levels[0]].items():
# TODO: @2021年3月22日 这里假设字典类型的数据实际指的是下一层调用。但数据本身是否可以是字典类型呢?
if isinstance(value, dict):
self.meta[self.META_CALL][key] = value
else:
self.meta[self.META_INPUT][key] = value
@property
def workflow_name(self):
return self.meta[self.META_NAME]
@property
def inputs(self) -> dict:
return self.meta[self.META_INPUT]
@property
def calls(self) -> list:
return list(self.meta[self.META_CALL].keys())
def call_input(self, call_name: str) -> dict:
return self.meta[self.META_CALL].get(call_name, {})
# 根据meta数据重新生成input
def __str__(self) -> str:
wf = self.workflow_name
out = {}
for k,v in self.inputs.items():
out[f"{wf}.{k}"] = v
for call_task in self.calls:
for k, v in self.call_input(call_task).items():
out[f'{wf}.{call_task}.{k}'] = v
return json.dumps(out, indent=self.indent, quote_keys=True, trailing_commas=False)
def update_input(self, key: str, value=None):
"""更新指定key对应的数据,若不提供第二个参数,则删除对应的key
Args:
key (str): 待更新或删除的key
value(any): 当设置为None时,删除key,否则更新key
"""
if value is None:
if key in self.meta[self.META_INPUT]:
del self.meta[self.META_INPUT][key]
else:
self.meta[self.META_INPUT][key] = value
def update_task_input(self, call_name: str, key: str, value=None):
# 1. 删除key
if value is None:
if key in self.meta[self.META_CALL][call_name]:
del self.meta[self.META_CALL][call_name][key]
# 2. 更新key
else:
self.meta[self.META_CALL][call_name][key] = value | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/input_processor.py | input_processor.py |
from __future__ import annotations
from collections import defaultdict
import os
import re
from typing import Any, Dict, List, OrderedDict
import yucebio.yc2.adaptor.util.wdl_v1_parser as WDL
class WDLProcessor(object):
# 使用2个空格作为缩进符
TOKEN_SEP= " "
PATTERN_INDENT_DETECT = re.compile(r"{\s*\n(\s+)")
def __init__(self, fileWDL: str, package_path: str = None) -> None:
self.fileWdl = fileWDL
# 获取组件的相对路径
self.package_path = package_path
if not package_path:
self.package_path = os.path.dirname(fileWDL)
# 保存文件原始内容
self.content = ""
self.line_contents = []
# wdl文档树
self.document: WDL.ParseTree = None
# 保存更新后的内容
self.replaces = []
self.tree_version: WDL.ParseTree = None
self.tree_imports: WDL.ParseTree = None
self.meta = defaultdict(list)
self.tab_size = 2
self._parse()
def __str__(self):
if not self.replaces:
return self.content
# return "\n".join([line for line in self.replaces if line and line.strip()])
empty_line = False
content = []
for line in self.replaces:
if line is None:
continue
if not line.strip():
# 跳过连续空行
if empty_line:
continue
empty_line = True
else:
empty_line = False
content.append(line)
return "\n".join(content)
def _parse(self):
"""解析WDL并转换为指定平台的新数据
"""
# 1. 加载入口WDL内容
with open(self.fileWdl, 'r', encoding='utf8') as r:
self.content = r.read()
self.tab_size = len(self.PATTERN_INDENT_DETECT.search(self.content).group(1))
self.line_contents = self.content.split("\n")
try:
self.document = WDL.parse(self.content)
except Exception as e:
raise RuntimeError(f"解析[ {self.fileWdl} ]异常: {e}")
# 2. 解析WDL内容为各个不同的代码块
self.traversal_document(self.document)
def traversal_document(self, treeDocument: WDL.ParseTree):
# 从 document中解析出 version, import, body
self.tree_version, self.tree_imports, tree_wdl_body = treeDocument.children
self._parse_import()
for file_body_element in tree_wdl_body.children:
# 解析出task
if not file_body_element.children:
continue
ele = file_body_element.children[0]
ele_name = ele.nonterminal.str
self.meta[ele_name].append(ele)
def _parse_import(self):
# $_gen0 = list($import)
_imported_wdls: Dict[str, _ImportItem] = {}
if self.tree_imports and self.tree_imports.children:
for tree_import in self.tree_imports.children:
import_item = _ImportItem(tree_import, self)
if import_item.path in _imported_wdls:
pre: _ImportItem = _imported_wdls[import_item.path]
raise RuntimeError(f"第{pre.line}行和第{import_item.line}行重复导入相同的wdl:{import_item.path}")
_imported_wdls[import_item.path] = import_item
self._imports = {item.namespace: item for item in _imported_wdls.values()}
@property
def imports(self) -> Dict[str, _ImportItem]:
"""导入内容
{
"namespace": _ImportItem
}
"""
return self._imports
def source_string(self, tree: WDL.ParseTree):
if isinstance(tree, WDL.Terminal):
return tree.source_string
start_line, start_col, end_line, end_col = self._get_range(tree)
if not start_line:
return ""
lines = self.line_contents[start_line-1: end_line]
if start_line == end_line:
return lines[0][start_col-1: end_col]
# 复制一份
lines = [str(l) for l in lines]
lines[0] = lines[0][start_col-1:]
lines[-1] = lines[-1][:end_col-1]
return "\n".join(lines)
def _get_range(self, tree: WDL.ParseTree):
start, end = self.first_terminal(tree), self.last_terminal(tree)
if not start:
return None, None, None, None
# command内部的terminal需要进一步处理换行符
end_code = end.source_string
end_lines = end_code.split("\n")
line_count = len(end_lines)
end_row, enc_col = end.line + line_count - 1, len(end_lines[-1]) + (end.col if line_count == 1 else 0)
return start.line, start.col, end_row, enc_col
def first_terminal(self, tree: WDL.ParseTree):
if isinstance(tree, WDL.Terminal):
return tree
for sub in tree.children:
t = self.first_terminal(sub)
if t:
return t
return None
def last_terminal(self, tree: WDL.ParseTree):
if isinstance(tree, WDL.Terminal):
return tree
for sub in reversed(tree.children):
t = self.last_terminal(sub)
if t:
return t
return None
def get_terminal(self, tree: WDL.ParseTree):
t = []
if isinstance(tree, WDL.Terminal):
return [tree]
for sub in tree.children:
t += self.get_terminal(sub)
return t
def replace_tree(self, new_code: str, raw: WDL.ParseTree=None, parent: WDL.ParseTree=None):
if new_code is None:
return
if not self.replaces:
self.replaces = self.content.split("\n")
# 区分插入和替换
if not raw:
# TODO: 处理插入代码
print("暂时不支持插入代码:", new_code)
return
start_line, start_col, end_line, end_col = self._get_range(raw)
if not start_line:
print("暂时不支持插入代码:", new_code)
# TODO: 处理插入代码
return
# TODO: 校验该区域是否发生过替换
if start_line == end_line:
line = self.replaces[start_line-1]
self.replaces[start_line-1] = line[:start_col-1] + new_code + line[end_col:]
return
# 复制一份
first, last = self.replaces[start_line-1], self.replaces[end_line-1]
# print("first:", repr(first), "\nlast: ", repr(last), "\nend_col:", end_col, len(self.replaces))
# 清空原来的数据
self.replaces[start_line-1: end_line] = [None] * (end_line - start_line +1)
self.replaces[start_line-1] = first[:start_col-1] + new_code
# 如果已经发生过替换,该区域内容为None;就不要在替换了
if last and last[end_col:]:
self.replaces[end_line-1] = last[end_col:]
return
# 从表达式中提取依赖
def _get_depency(self, expr: WDL.ParseTree, debug=False):
"""从表达式中提取依赖的其他call
Args:
expr (WDL.ParseTree): [description]
原理:
若某个call依赖其他call则必然存在{taskname.out_name}格式的表达式
$e = $e <=> :dot :identifier -> MemberAccess( value=$0, member=$2 )
暂时只考虑 scatter 和 input 中出现的表达式
"""
if debug:
print(self.source_string(expr))
# 表达式可能存在嵌套
depency = set()
ast = expr.ast()
if hasattr(ast, "name") and ast.name == 'MemberAccess':
# expr = x.y
s = self.source_string(expr).split('.')
# depency.update({s[0]: s[1]})
depency.add(s[0])
else:
for child in expr.children:
if isinstance(child, WDL.Terminal):
continue
depency.update(self._get_depency(child, debug))
return depency
class _ImportItem(object):
"""管理import的辅助类: 不考虑alias, 需要有as
$import = :import $static_string $_gen5 $_gen6 -> Import( uri=$1, namespace=$2, aliases=$3 )
$import = :import $static_string optional($import_namespace) list($import_alias)
$import_namespace = :as :identifier -> $1
$import_alias = :alias :identifier :as :identifier -> ImportAlias( old_name=$1, new_name=$3 )
"""
def __init__(self, tree_import: WDL.ParseTree, processor: WDLProcessor) -> None:
self.tree = tree_import
self.processor = processor
# 自定义属性
self.path = ""
self.line = 0
self.namespace = ""
self.wdl = None
self._parse()
@property
def meta(self):
return {
"line": self.line,
"path": self.path,
"namespace": self.namespace
}
def _parse(self):
_str, _static_string, _gen5, _gen6 = self.tree.children
# 包含引号的内容
self.line = _str.line
self.path = self.processor.source_string(_static_string.children[1]).strip(' \'"')
# relpath = os.path.join(os.path.dirname(self.processor.fileWdl), self.path)
relpath = os.path.join(self.processor.package_path, self.path)
self.wdl = TaskProcessor(relpath, self.processor.package_path)
if not _gen5.children:
raise RuntimeError(f"line #{self.line} 导入wdl时需要指定as内容")
_import_namespace: WDL.ParseTree = _gen5.children[0]
identifier: WDL.Terminal = _import_namespace.children[1]
self.namespace = identifier.source_string
class WorkflowProcess(WDLProcessor):
"""Workflow处理器
1. 有且只能由1个workflow
2. 只支持version, imports, workflow元素
3. workflow中仅支持inputs, scatter, call
"""
def __init__(self, fileWDL: str, package_path: str = None) -> None:
self.tree_workflow: WDL.ParseTree = None
self.workflow_meta = {
"inputs": {},
"calls": {}
}
super().__init__(fileWDL, package_path)
def _parse(self):
super()._parse()
if self.meta.get('task'):
raise RuntimeError("请不要在workflow中定义task")
# 校验1: 存在且只能存在1个workflow
if not self.meta.get('workflow'):
raise RuntimeError("未定义workflow")
if len(self.meta['workflow']) != 1:
raise RuntimeError("不允许同时定义多个workflow")
self.tree_workflow = self.meta['workflow'][0]
self._traversal_workflow(self.tree_workflow)
def _traversal_workflow(self, tree_workflow: WDL.ParseTree):
"""解析workflow,生成input对应关系
Args:
tree_workflow (WDL.ParseTree)
1. workflow中可能存在input
2. call中可能存在重新赋值
Return:
{
"name": "{workflow_name}",
"input": {},
"tasks": [
{"name": "", "inputs": {}}, ...
]
}
"""
supported_elements = ['call', 'scatter', 'inputs']
self.tree_workflow = tree_workflow
# $workflow = :workflow :identifier :lbrace $_gen15 :rbrace -> Workflow( name=$1, body=$3 )
self.workflow_name = tree_workflow.children[1].source_string.strip()
tree_gen15: WDL.ParseTree = tree_workflow.children[3]
# $_gen15 = list($wf_body_element)
for wf_body_element in tree_gen15.children:
element_name = wf_body_element.children[0].nonterminal.str
if element_name not in supported_elements:
raise RuntimeError(f"检测到不支持的元素{element_name}, workflow中仅支持{supported_elements}")
parse_func = getattr(self, f"_parse_workflow_{element_name}", None)
if not parse_func:
continue
parse_func(wf_body_element.children[0])
# 所有call处理完之后,生成call vs task对应关系
# 遍历calls初始化被调用task对应关系
call_tasks = {}
for wp_call_item in self.calls.values():
# wp_call_item.inputs
ns = wp_call_item.namespace
task_name = wp_call_item.task_name
if ns not in call_tasks:
call_tasks[ns] = {}
# 同一个task可能重复调用,并赋予不同的alias
if task_name not in call_tasks[ns]:
call_tasks[ns][task_name] = []
call_tasks[ns][task_name].append(wp_call_item)
self.call_tasks = call_tasks
# 检测是否存在未使用的import内容
for ns, import_item in self.imports.items():
if ns not in call_tasks:
raise RuntimeError(f"Line #{import_item.line} 请移除未使用的导入内容 {import_item.path}")
def _parse_workflow_call(self, tree_call: WDL.ParseTree, depency: dict=None):
"""解析workflow中出现的call内容"""
# $call = :call :fqn optional($alias) optional($call_brace_block) -> Call(task=$1, alias=$2, body=$3)
print("in parser call", depency)
item = _WorkflowCallItem(tree_call, self, depency)
self.workflow_meta['calls'][item.alias] = item
@property
def name(self):
return self.workflow_name
@property
def inputs(self) -> dict:
"""workflow级别的输入数据
Returns:
dict: { key: {type, identifier, defalut?}}
"""
return self.workflow_meta['inputs']
@property
def calls(self) -> Dict[str, _WorkflowCallItem]:
return self.workflow_meta['calls']
def _parse_workflow_inputs(self, tree_inputs: WDL.ParseTree, depency: dict=None):
"""解析workflow中的input内容,后期可以与输入文件中的workflow_inputs做校验
"""
# $inputs = :input :lbrace $_gen10 :rbrace -> Inputs( inputs=$2 )
if not tree_inputs.children:
return
tree_gen10 = tree_inputs.children[2]
# $_gen10 = list($input_declaration)
for input_declaration in tree_gen10.children:
# $input_declaration = $type_e :identifier $_gen13
type_e, indetifier, tree_gen13 = input_declaration.children
# TODO: 找到与资源相关的变量, 考虑call中可能使用了其他参数名来管理资源
# 提取变量名 类型 和 默认值
_meta = {
"type": self.source_string(type_e),
"identifier": self.source_string(indetifier).strip(),
}
if tree_gen13.children:
# 提取默认值
# $_gen13 = optional($setter)
# $setter = :equal $e -> $1
_meta['default'] = self.source_string(tree_gen13.children[0].children[1])
self.workflow_meta['inputs'][_meta['identifier']] = _meta
def _parse_workflow_scatter(self, tree_scatter: WDL.ParseTree, depency: dict=None):
# $scatter = :scatter :lparen :identifier :in $e :rparen :lbrace $_gen15 :rbrace
# 从第四部分解析出依赖信息
tree_e = tree_scatter.children[4]
depency = self._get_depency(tree_e, True)
if depency:
print("get 111", depency)
tree_gen15 = tree_scatter.children[-2]
# $_gen15 = list($wf_body_element)
for wf_body_element in tree_gen15.children:
element_name = wf_body_element.children[0].nonterminal.str
if element_name not in ['call', 'scatter', 'declaration']:
raise RuntimeError(f"检测到不支持的元素{element_name}, scatter中仅支持call")
parse_func = getattr(self, f"_parse_workflow_{element_name}", None)
if not parse_func:
continue
parse_func(wf_body_element.children[0], depency)
def generate_graph(self):
"""遍历每个call,生成依赖图
"""
node_with_depth = {}
visited = {}
def cal_depth(dep):
pass
for task_name, task_item in self.calls.items():
for dep in task_item.depency:
dep_item = self.calls[dep]
if dep not in visited:
# 计算依赖项的深度
pass
class _WorkflowCallItem(object):
"""Workflow Call管理工具:支持修改input内容
Args:
object ([type]): [description]
"""
def __init__(self, tree: WDL.ParseTree, processor: WorkflowProcess, depency: set = None) -> None:
self.tree = tree
self.processor = processor
# 自定义属性
self.namespace = ""
self.task_name = ""
self.alias = ""
self.inputs = OrderedDict()
self.depency = set(depency) if depency is not None else set()
self._parse()
def _parse(self):
# $call = :call :fqn $_gen16 $_gen17 -> Call( task=$1, alias=$2, body=$3 )
_, name, gen16, gen17 = self.tree.children
self.namespace, self.task_name = self.processor.source_string(name).strip().split('.')
# $gen16 = optional($alias)
# $alias = :as :identifier
if not gen16.children:
raise RuntimeError(f"[{self.processor.fileWdl}@{self.processor.workflow_name}] [{self.namespace}.{self.task_name}] 需要指定AS")
self.alias = self.processor.source_string(gen16.children[0].children[1]).strip()
self.inputs = {}
# $gen17 = optional($call_brace_block)
if not gen17.children:
return
call_brace_block = gen17.children[0]
# $call_brace_block = :lbrace $gen18 :rbrace
gen18 = call_brace_block.children[1]
# $gen18 = optional($call_body)
if not gen18.children:
return
call_body = gen18.children[0]
# $call_body = :input :colon $_gen19
gen19 = call_body.children[2]
# gen19 = list(input_kv :colon)
for child in gen19.children:
if isinstance(child, WDL.Terminal):
continue
# $input_kv = :identifier :equal $e
identifier, _, expr = child.children
self.inputs[identifier.source_string.strip()] = self.processor.source_string(expr).strip()
self.depency.update(self.processor._get_depency(expr))
def __str__(self):
return self.tree.ast().dumps(indent=1)
class TaskProcessor(WDLProcessor):
def __init__(self, fileWDL: str, package_path: str = None) -> None:
self.meta_tasks: List[_TaskItem] = []
self.tree_tasks = []
super().__init__(fileWDL, package_path)
def _parse(self):
super()._parse()
if self.meta.get('workflow'):
raise RuntimeError("请不要在task中定义workflow")
if self.meta.get('imports'):
raise RuntimeError("请不要在task中使用imports")
# 依次处理每个task
for task_tree in self.meta['task']:
self.meta_tasks.append(_TaskItem(task_tree, self))
def __str__(self):
# 依次对每个子task执行__str__
for ti in self.meta_tasks:
ti.do_update()
return super().__str__()
class _TaskItem(object):
# input中的保留字段
RESERVED_INPUT_TOKENS = ['cluster']
# 需要增加一个资源类型: 按需还是竞价
RUNTIME_RESCOURCE_KEYS = ['cpu', 'memory', 'rescource_type']
def __init__(self, tree_task:WDL.ParseTree, processor: TaskProcessor) -> None:
super().__init__()
self.tree = tree_task
self.processor = processor
self.token_tab = " " * self.processor.tab_size
# 自定义属性
self.name = ""
self.meta: Dict[str, WDL.ParseTree] = {}
self._inputs = {}
self._runtime = {}
# 当前任务的可变资源
self.rescources = {}
self._dirty = {}
self._parse()
def do_update(self):
"""依次检查每个关键元素是否发生变更,若有变更,则执行替换
"""
# 1. 处理input
if self._dirty.get('input'):
# new_input = f"\n{self.token_tab}input " + '{'
new_input = f"input " + '{'
for k, item in self.inputs.items():
new_input += "\n" + self.token_tab * 2 + "{type} {name}".format(**item)
if item.get('default'):
new_input += f" = {item['default']}"
new_input += "\n" + self.token_tab + '}'
self.processor.replace_tree(new_input, self.meta['inputs'], parent=self.tree)
# 2. 处理runtime
if self._dirty.get('runtime'):
new_runtime = "runtime {"
# new_runtime = "\n" + self.token_tab + "runtime {"
for k,v in self.runtime.items():
new_runtime += '\n' + self.token_tab*2 + f"{k}: {v}"
new_runtime += '\n' + self.token_tab + '}'
self.processor.replace_tree(new_runtime, self.meta['runtime'], parent=self.tree)
# 3. 处理command
if self._dirty.get('command'):
new_command = "command <<<\n" + self._new_command_content + "\n" + self.token_tab + ">>>"
self.processor.replace_tree(new_command, self.meta['command'], parent=self.tree)
@property
def inputs(self):
return self._inputs
@property
def runtime(self) -> dict:
return self._runtime
def _parse(self):
task_name: WDL.Terminal = self.tree.children[1]
tree_task_body: WDL.ParseTree = self.tree.children[3]
task = {"tree": self.tree, "name": task_name.source_string, "simg": "", "e_simg": False}
self.name: str = task_name.source_string
for task_section in tree_task_body.children:
# outputs
if not (task_section.children and task_section.children[0].nonterminal.str in ["runtime", "command", "inputs"]):
continue
tree_section = task_section.children[0]
section_name = tree_section.nonterminal.str
self.meta[section_name] = tree_section
# print(">>>>>> parse", self.processor.fileWdl, self.name)
self._parse_inputs()
self._parse_runtime()
self._parse_command()
# 根据 runtime 和 inputs 计算当前任务的可变资源字段
for k in self.RUNTIME_RESCOURCE_KEYS:
if k not in self.runtime:
continue
runtime_value = self.runtime[k]
if runtime_value in self.inputs:
input_resource_item = self.inputs[runtime_value]
# 若资源变量有默认值,则将CPU和MEM默认值转换为数值
if input_resource_item.get('default'):
if k != 'rescource_type':
try:
input_resource_item['default'] = int(input_resource_item['default'])
except Exception:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} INPUT中的字段[{runtime_value}]的默认值必须是整数")
self.rescources[runtime_value] = {**input_resource_item, "runtime": k}
def _parse_inputs(self):
tree_inputs = self.meta['inputs']
# $inputs = :input :lbrace $_gen10 :rbrace -> Inputs( inputs=$2 )
tree_gen10 = tree_inputs.children[2]
# $_gen10 = list($input_declaration)
if not tree_gen10.children:
return
for tree_input_declaration in tree_gen10.children:
_meta = {}
# $input_declaration = $type_e :identifier $_gen13
_type, identifier, gen13 = tree_input_declaration.children
_meta['type'] = self.processor.source_string(_type).strip()
_meta['name'] = self.processor.source_string(identifier).strip()
# _meta['type'] = self.processor.source_string(_type).strip()
if gen13.children:
# $gen13 = optional($setter)
# $setter = :equal $e -> $1
_, expr = gen13.children[0].children
_meta['default'] = self.processor.source_string(expr).strip()
self._inputs[_meta['name']] = _meta
if 'simg' not in self.inputs or self.inputs['simg']['type'] != 'String':
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} INPUT中必须提供[String simg]")
def _parse_runtime2(self):
# $runtime = :runtime $rt_map -> Runtime(map=$1)
ast = self.meta['runtime'].ast()
runtime_maps: List[WDL.Ast] = ast.attr('map')
for runtime_map in runtime_maps:
# $kv = :identifier :colon $e -> RuntimeAttribute(key=$0, value=$2)
key = runtime_map.attr('key').source_string.strip()
value = runtime_map.attr('value')
if isinstance(value, WDL.Terminal):
value = value.source_string.strip()
self._runtime[key] = value
# validate 1: 必须提供simg
if 'simg' not in self._runtime:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} runtime中必须提供simg")
# validate 2: 只能使用memory
if 'mem' in self._runtime:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} runtime中请使用memory代替mem")
def _parse_runtime(self):
tree = self.meta['runtime']
# $runtime = :runtime $rt_map -> Runtime(map=$1)
tree_rt_map: WDL.ParseTree = tree.children[1]
# $rt_map = :lbrace $_gen11 :rbrace
gen11: WDL.ParseTree = tree_rt_map.children[1]
# $_gen11 = list($kv)
for tree_kv in gen11.children:
# $kv = :identifier :colon $e
identifier: WDL.Terminal = tree_kv.children[0]
tree_expr: WDL.ParseTree = tree_kv.children[2]
key = identifier.source_string.strip()
value = self.processor.source_string(tree_expr)
self._runtime[key] = value
if 'simg' not in self._runtime:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} runtime中必须提供simg")
# validate 2: 只能使用memory
if 'mem' in self._runtime:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} runtime中请使用memory代替mem")
def _parse_command(self):
# runtime中必须提供simg
if 'simg' not in self.runtime:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} RUNTIME中必须提供simg参数")
simg = self.runtime['simg']
# runtime的simg必须是变量
if simg not in self.inputs:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} RUNTIME中的simg参数不是变量或找不到input中对应的simg变量")
tree_gen8: WDL.ParseTree = self.meta['command'].children[2]
self.command_content = self.processor.source_string(tree_gen8).strip('\n')
if not re.search(r"set\s+-e\s*\n", self.command_content):
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} COMMAND必须以set -e开头,且必须换行")
self._check_command_indent_size(self.command_content)
def _check_command_indent_size(self, command_content: str):
"""以命令的第一行为基准,后续行按照第一行的缩进格式进行调整
"""
min_space = self.processor.tab_size * 2
first_line, line_index = True, 0
self.command_content_lines = []
for line in command_content.split('\n'):
line_index += 1
tmp = line.lstrip()
self.command_content_lines.append(tmp)
# 跳过空行
if not tmp:
continue
space = len(line) - len(tmp)
if first_line:
# 首行缩进必须正确
if space != min_space:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} COMMAND首行缩进({space}个空格)不正确,请按照{min_space}个空格(2个tab)设置首行缩进")
# 首行必须是set -e
if 'set -e' not in tmp:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} COMMAND必须以set -e开头 {repr(tmp)}")
first_line = False
if space < min_space:
raise RuntimeError(f"{self.processor.fileWdl}@{self.name} COMMAND 第{line_index}行缩进不正确({tmp[:10]}...)")
def update_input(self, key: str, value_type: str = None, default: Any = None):
"""更新input内容,当value_type为None时,表示删除该key
Args:
key (str): 待更新的input内容
value_type (str, optional): 新的字段类型,设置为None时表示删除字段
default (Any, optional): 设置新字段默认值. Defaults to None.
"""
self._dirty['input'] = True
# value_type未设置时,表示删除字段
if not value_type:
if key in self._inputs:
del self._inputs[key]
# 否则,更新为新的类型,并设置默认值
else:
self._inputs[key] = {"type": value_type, 'name': key}
if default:
self._inputs[key]['default'] = default
def delete_input(self, key: str):
return self.update_input(key, value_type=None)
def update_runtime(self, key: str, value: Any = None):
"""更新或删除runtime内容,当value为None时,删除对应的key
Args:
key (str): 待更新或删除的runtime键
value (Any, optional): 更新后的值. Defaults to None.
"""
self._dirty['runtime'] = True
# value设置为None时,删除对应的key
if not value:
if key in self._runtime:
del self._runtime[key]
# 否则,直接更新为新的数据
else:
self._runtime[key] = value
def delete_runtime(self, key: str):
return self.update_runtime(key, None)
def delete_content(self):
self.processor.replace_tree("\n", self.tree)
def update_command(self, new_command: str):
self._new_command_content = new_command
self._dirty['command'] = True | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/wdl_processor.py | wdl_processor.py |
import datetime
import ldap3
from functools import lru_cache
import ldap3.core.exceptions
from . import types
class LDAP(object):
def __init__(self) -> None:
super().__init__()
@lru_cache()
def get_server(self):
return ldap3.Server('ldap.yucebio.com')
def get_connection(self):
conn = ldap3.Connection(
server=self.get_server(),
read_only=True,
client_strategy=ldap3.SYNC,
check_names=True,
raise_exceptions=True
)
conn.bind()
return conn
# 1. 检查用户是否存在
def get_user(self, username: str) -> types.UserType:
connection = self.get_connection() # type: ldap3.Connection
try:
connection.search(f'uid={username},ou=People,dc=nodomain', '(objectclass=inetOrgPerson)', attributes=ldap3.ALL_ATTRIBUTES)
except ldap3.core.exceptions.LDAPNoSuchObjectResult:
return {}
data = None
if len(connection.response) > 0:
data = connection.response[0]['attributes']
data['dn'] = connection.response[0]['dn']
connection.unbind()
return self.format_from_ldap(data)
def format_from_ldap(self, ldap_user_info: dict):
"""[summary]
Args:
ldap_user_info (dict): [description]
"""
user_id = ldap_user_info['uid'][0]
item = {
"name": user_id,
# "name_chs": ldap_user_info.get('displayName', user_id),
# "dingdingId": ldap_user_info.get('pager', [None])[0],
# "expiry_at": datetime.datetime.now() + datetime.timedelta(days=1), # 过期时间 24h
}
return item
# 登录并返回当前用户信息
def check_login(self, username, password):
conn = ldap3.Connection(
server=self.get_server(),
read_only=True,
user=f'uid={username},OU=People,DC=nodomain',
password=password,
client_strategy=ldap3.SYNC,
check_names=True,
raise_exceptions=True
)
try:
conn.bind()
except ldap3.core.exceptions.LDAPInvalidCredentialsResult:
raise RuntimeError("用户名或密码错误")
conn.unbind() | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/ldap.py | ldap.py |
import dateutil.parser
import re
import sys
from typing import OrderedDict
import requests
from yucebio.yc2.adaptor.util.config import Config
import click
from . import types
config = Config(check_user=False)
class Monitor:
def __init__(self, backend_name: str = None, check_user=True) -> None:
if check_user:
config.check_user()
self.api = config.api
self.backend_config : types.CromwellBackendType = None
if backend_name:
self.init_backend_config(backend_name)
def init_backend_config(self, backend_alias: str):
"""在预设和自定义backend中找到最匹配的
"""
if self.backend_config and self.backend_config["alias"] == backend_alias:
return
self.backend_config = config.get_backend_config(backend_alias)
@property
def owner(self):
return config.get('owner', '')
def get(self, jobid: str, server_alias: str, auto_update: bool = True):
"""从cromwell api中获取作业最新状态
Args:
jobid (str): cromwell 作业id
server_alias (str): cromwell server地址
auto_update (bool): 检测到任务完成时,是否自动更新到数据库
"""
cromwell_job = CromwellJob(jobid, host=self.backend_config["host"])
cromwell_job.get_metadata()
return cromwell_job
def query(self, params: dict, backend_name: str):
"""基于Cromwell API接口查询数据,Refer to https://cromwell.readthedocs.io/en/stable/api/RESTAPI/#workflowqueryparameter
"""
# api = config.get_cromwell_backend(backend_name)["host"]
api = self.backend_config["host"]
url = f"{api}/api/workflows/v1/query"
try:
rsp = requests.get(url, params=params)
if not rsp.ok:
print(url, params)
raise RuntimeError(rsp.reason)
return rsp.json()
except Exception as e:
raise e
def list_jobs(self, params: dict={}, show_detail: bool = False):
"""查看本人所有任务
"""
page = params.get('page', 1)
pageSize = params.get('page_size', 10)
skip = (page - 1) * pageSize
if skip <= 0:
skip = 0
api_params = {k:v for k,v in params.items() if k not in ['page', 'page_size', 'backend_name']}
api_params['owner'] = self.owner
if params.get('backend_name'):
self.init_backend_config(params['backend_name'])
backend = self.backend_config.get('platform', self.backend_config.get('backend'))
api_params['backend.backend'] = backend
workflows, totals = self.api.get_workflows(api_params, paginations={"offset": skip, "limit": pageSize})
if not workflows:
return
click.secho(f"第{skip}-{skip + len(workflows)}条,总共 {totals} 条数据", fg="green")
# 打印表头
format = '{status:10s}\t{count}\t{workflow_name}\t{duration}\t{sample_ids}\t{prefix}\t{workdir}\t{url}'
header = {
"status": "Status", # Succeeded
"count": "TaskCount",
"prefix": "Prefix/Project", # 20211116.ClinicRapid.2103062.MT1011.104406
"sample_ids": "Samples", # DN2003922SLZDA26
"workflow_name": "WorkflowName",
"workdir": "Workdir",
"duration": "Start/Duration",
"url": "Metadata",
}
print(format.format(**header))
patt_datetime = re.compile(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z')
for workflow in workflows:
# self.format_api_workflow(workflow, show_detail=show_detail)
row = {k: workflow.get(k, '-') for k in header}
if workflow.get('cromwell_id'):
backend_host = workflow["backend"]["host"]
row['url'] = f"{backend_host}/api/workflows/v1/{workflow['cromwell_id']}/metadata"
project = workflow.get('project', 'NA')
if project == workflow.get('prefix', 'NA'):
project = '-'
row['prefix'] = f"{row['prefix']}/{project}"
# 计算分析时长
start, end = '', ''
if workflow.get('start') and patt_datetime.match(workflow['start']):
start = dateutil.parser.isoparse(workflow['start'])
if workflow.get('end') and patt_datetime.match(workflow['end']):
end = dateutil.parser.isoparse(workflow['end'])
if start and end:
duration = (end - start).seconds/3600
start = start.strftime('%Y-%m-%dT%H:%M:%S')
row['duration'] = f"{start}/{duration:.2f}h"
# 计算任务数目
count_running = len(workflow.get('running_tasks', []))
count_done = len(workflow.get('calls', []))
count_total = workflow.get('wdl', {}).get("task_count", "-")
row['count'] = f"{count_running}/{count_done}/{count_total}"
print(format.format(**row))
if workflow["status"] == 'Running' and show_detail:
for running_task in workflow.get("running_tasks", []):
print(click.style(f"RUNNING:\t{running_task}", fg="yellow"))
if show_detail:
for r in workflow.get("failures", []):
print(click.style(f"FAIL_REASON:\t{r}", fg="red"), file=sys.stderr)
def format_api_workflow(self, workflow: types.WorkflowType, show_detail: bool = False):
backend_host = workflow["backend"]["host"]
url = "-"
if workflow.get('cromwell_id'):
url = f"{backend_host}/api/workflows/v1/{workflow['cromwell_id']}/metadata"
msg = f'{workflow["status"]:10s}\t{workflow.get("prefix", "-"):40s}\t{workflow.get("sample_ids", "-"):32s}\t{workflow.get("workflow_name", "-"):15s}\t\t {url}\t{workflow.get("workdir", "-")}'
duration = f"\t{workflow.get('start', '-')}:{workflow.get('end', '-')}"
msg += duration
if workflow["status"] == 'Running' and show_detail:
for running_task in workflow.get("running_tasks", []):
msg += click.style(f"\nRUNNING:\t{running_task}", fg="yellow")
print(msg)
if show_detail:
for r in workflow.get("failures", []):
print(click.style(f"\nFAIL_REASON:\t{r}", fg="red"), file=sys.stderr)
class CromwellJob:
def __init__(self, cromwell_id: str, host: str=None) -> None:
self.cromwell_id = cromwell_id
self.api = host
self.metadata = {}
self.call_details = []
# 需要从inputs中提取的额外内容
self.owner = ""
self.prefix = ""
self.samples = ""
def get_metadata(self):
"""从cromwell api中获取作业最新状态
"""
if self.metadata:
return
url = f"{self.api}/api/workflows/v1/{self.cromwell_id}/metadata"
rsp = requests.get(url)
if not rsp.ok:
raise RuntimeError(f"{url}\t{rsp.reason}")
metadata: dict = rsp.json()
self.parse_metadata(metadata)
def parse_metadata(self, metadata: dict):
"""解析metadata数据
"""
self.metadata = metadata
if not self.metadata:
return
self.status = self.metadata.get('status')
for k in ["workflowName", "id", "status", "submission", "start", "end"]:
self.__dict__[k] = self.metadata.get(k, "")
# 解析calls
calls = self.metadata.get('calls')
if isinstance(calls, dict):
for task_name, task_items in calls.items():
idx = -1
for task_item in task_items:
idx += 1
info = {
k: task_item.get(k, '-') for k in [
"executionStatus", "jobId", "backend", "start", "end", "callRoot",
]
}
failures = task_item.get('failures')
if failures:
failures = self.parse_failures(failures)
self.call_details.append((task_name, idx, info, failures))
self.parse_inputs()
def parse_inputs(self):
"""解析inputs,提取一些必要信息"""
inputs = self.metadata.get('inputs', {})
if inputs:
self.prefix = inputs.get('prefix', 'NA')
tumor_id = inputs.get('tumor_id', None)
normal_id = inputs.get('normal_id', None)
rna_id = inputs.get('rna_id', None)
sample = "-VS-".join([v for v in [tumor_id, normal_id] if v])
sample = ",".join([v for v in [sample, rna_id] if v])
self.samples = sample
self.owner = inputs.get('owner', "")
def parse_failures(self, failures: list):
reasons = []
for failure in failures:
casedBy = failure.get('causedBy')
if casedBy:
reasons += self.parse_failures(failure['causedBy'])
else:
if failure.get('message'):
reasons.append(failure['message'])
return reasons
def format(self):
key_lables = OrderedDict([
("workflowName", "流程名称"),
("id", "Workflow Id"),
("status", "状态"),
("submission", "提交时间"),
("start", "开始时间"),
("end", "结束时间"),
# ("prefix", "分析项目号"),
# ("samples", "样本")
])
basic_infos = {k: self.metadata.get(k, "-") for k in key_lables}
url = f"{self.api}/api/workflows/v1/{self.cromwell_id}/metadata"
basic_infos["id"] = url
msg = f"{basic_infos['status']}\t{self.prefix:15s}\t{self.samples:20s}\t{basic_infos['workflowName']:15s}\t{url}\t{basic_infos['submission']}"
if self.status == 'Running':
for running_task in self.current_running_tasks():
msg += click.style(f"\nRUNNING:\t{running_task}", fg="yellow")
print(msg)
for r in self.fail_reason():
print(click.style(f"\nFAIL_REASON:\t{r}", fg="red"), file=sys.stderr)
def current_running_tasks(self):
tasks = []
for call in self.call_details:
task_name, idx, info, failures = call
if info.get('executionStatus') == 'Running':
tasks.append(f"{task_name}[{idx}]\t{info['jobId']}\t{info['start']}")
return tasks
def fail_reason(self):
if not self.call_details:
# 直接从顶级的failures中提取错误信息
return self.parse_failures(self.metadata.get('failures', []))
reasons = []
for call in self.call_details:
task_name, idx, info, failures = call
if not failures:
continue
reasons += [f"{task_name}[{idx}]\t{f}" for f in failures]
return reasons | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/monitor.py | monitor.py |
import sys
import os
import re
import base64
import argparse
from collections import OrderedDict
# Common Code #
def parse_tree_string(parsetree, indent=None, b64_source=True, indent_level=0, debug=False):
indent_str = (' ' * indent * indent_level) if indent else ''
if isinstance(parsetree, ParseTree):
children = [parse_tree_string(child, indent, b64_source, indent_level+1, debug) for child in parsetree.children]
debug_str = parsetree.debug_str() if debug else ''
if indent is None or len(children) == 0:
return '{0}({1}: {2}{3})'.format(indent_str, parsetree.nonterminal, debug_str, ', '.join(children))
else:
return '{0}({1}:{2}\n{3}\n{4})'.format(
indent_str,
parsetree.nonterminal,
debug_str,
',\n'.join(children),
indent_str
)
elif isinstance(parsetree, Terminal):
return indent_str + parsetree.dumps(b64_source=b64_source)
def ast_string(ast, indent=None, b64_source=True, indent_level=0):
indent_str = (' ' * indent * indent_level) if indent else ''
next_indent_str = (' ' * indent * (indent_level+1)) if indent else ''
if isinstance(ast, Ast):
children = OrderedDict([(k, ast_string(v, indent, b64_source, indent_level+1)) for k, v in ast.attributes.items()])
if indent is None:
return '({0}: {1})'.format(
ast.name,
', '.join('{0}={1}'.format(k, v) for k, v in children.items())
)
else:
return '({0}:\n{1}\n{2})'.format(
ast.name,
',\n'.join(['{0}{1}={2}'.format(next_indent_str, k, v) for k, v in children.items()]),
indent_str
)
elif isinstance(ast, list):
children = [ast_string(element, indent, b64_source, indent_level+1) for element in ast]
if indent is None or len(children) == 0:
return '[{0}]'.format(', '.join(children))
else:
return '[\n{1}\n{0}]'.format(
indent_str,
',\n'.join(['{0}{1}'.format(next_indent_str, child) for child in children]),
)
elif isinstance(ast, Terminal):
return ast.dumps(b64_source=b64_source)
class Terminal:
def __init__(self, id, str, source_string, resource, line, col):
self.__dict__.update(locals())
def getId(self):
return self.id
def ast(self):
return self
def dumps(self, b64_source=True, **kwargs):
source_string = base64.b64encode(self.source_string.encode('utf-8')).decode('utf-8') if b64_source else self.source_string
return '<{resource}:{line}:{col} {terminal} "{source}">'.format(
resource=self.resource,
line=self.line,
col=self.col,
terminal=self.str,
source=source_string
)
def __str__(self):
return self.dumps()
class NonTerminal():
def __init__(self, id, str):
self.__dict__.update(locals())
self.list = False
def __str__(self):
return self.str
class AstTransform:
pass
class AstTransformSubstitution(AstTransform):
def __init__(self, idx):
self.__dict__.update(locals())
def __repr__(self):
return '$' + str(self.idx)
def __str__(self):
return self.__repr__()
class AstTransformNodeCreator(AstTransform):
def __init__( self, name, parameters ):
self.__dict__.update(locals())
def __repr__( self ):
return self.name + '( ' + ', '.join(['%s=$%s' % (k,str(v)) for k,v in self.parameters.items()]) + ' )'
def __str__(self):
return self.__repr__()
class AstList(list):
def ast(self):
retval = []
for ast in self:
retval.append(ast.ast())
return retval
def dumps(self, indent=None, b64_source=True):
args = locals()
del args['self']
return ast_string(self, **args)
class ParseTree():
def __init__(self, nonterminal):
self.__dict__.update(locals())
self.children = []
self.astTransform = None
self.isExpr = False
self.isNud = False
self.isPrefix = False
self.isInfix = False
self.nudMorphemeCount = 0
self.isExprNud = False # true for rules like _expr := {_expr} + {...}
self.list_separator_id = None
self.list = False
def debug_str(self):
from copy import deepcopy
def h(v):
if v == False or v is None:
return str(v)
from xtermcolor import colorize
return colorize(str(v), ansi=190)
d = deepcopy(self.__dict__)
for key in ['self', 'nonterminal', 'children']:
del d[key]
f = {k: v for k, v in d.items() if v != False and v is not None}
return ' [{}]'.format(', '.join(['{}={}'.format(k,h(v)) for k,v in f.items()]))
def add(self, tree):
self.children.append( tree )
def is_compound_nud(self):
return isinstance(self.children[0], ParseTree) and \
self.children[0].isNud and \
not self.children[0].isPrefix and \
not self.isExprNud and \
not self.isInfix
def ast(self):
if self.list == True:
r = AstList()
if len(self.children) == 0:
return r
for child in self.children:
if isinstance(child, Terminal) and self.list_separator_id is not None and child.id == self.list_separator_id:
continue
r.append(child.ast())
return r
elif self.isExpr:
if isinstance(self.astTransform, AstTransformSubstitution):
return self.children[self.astTransform.idx].ast()
elif isinstance(self.astTransform, AstTransformNodeCreator):
parameters = OrderedDict()
for name, idx in self.astTransform.parameters.items():
if idx == '$':
child = self.children[0]
elif self.is_compound_nud():
if idx < self.children[0].nudMorphemeCount:
child = self.children[0].children[idx]
else:
index = idx - self.children[0].nudMorphemeCount + 1
child = self.children[index]
elif len(self.children) == 1 and not isinstance(self.children[0], ParseTree) and not isinstance(self.children[0], list):
return self.children[0]
else:
child = self.children[idx]
parameters[name] = child.ast()
return Ast(self.astTransform.name, parameters)
else:
if isinstance(self.astTransform, AstTransformSubstitution):
return self.children[self.astTransform.idx].ast()
elif isinstance(self.astTransform, AstTransformNodeCreator):
parameters = OrderedDict()
for name, idx in self.astTransform.parameters.items():
parameters[name] = self.children[idx].ast()
return Ast(self.astTransform.name, parameters)
elif len(self.children):
return self.children[0].ast()
else:
return None
def dumps(self, indent=None, b64_source=True, debug=False):
args = locals()
del args['self']
return parse_tree_string(self, **args)
class Ast():
def __init__(self, name, attributes):
self.__dict__.update(locals())
def attr(self, attr):
return self.attributes[attr]
def dumps(self, indent=None, b64_source=True):
args = locals()
del args['self']
return ast_string(self, **args)
class SyntaxError(Exception):
def __init__(self, message):
self.__dict__.update(locals())
def __str__(self):
return self.message
class TokenStream(list):
def __init__(self, arg=[]):
super(TokenStream, self).__init__(arg)
self.index = 0
def advance(self):
self.index += 1
return self.current()
def last(self):
return self[-1]
def current(self):
try:
return self[self.index]
except IndexError:
return None
class DefaultSyntaxErrorHandler:
def __init__(self):
self.errors = []
def _error(self, string):
error = SyntaxError(string)
self.errors.append(error)
return error
def unexpected_eof(self):
return self._error("Error: unexpected end of file")
def excess_tokens(self):
return self._error("Finished parsing without consuming all tokens.")
def unexpected_symbol(self, nonterminal, actual_terminal, expected_terminals, rule):
return self._error("Unexpected symbol (line {line}, col {col}) when parsing parse_{nt}. Expected {expected}, got {actual}.".format(
line=actual_terminal.line,
col=actual_terminal.col,
nt=nonterminal,
expected=', '.join(expected_terminals),
actual=actual_terminal
))
def no_more_tokens(self, nonterminal, expected_terminal, last_terminal):
return self._error("No more tokens. Expecting " + expected_terminal)
def invalid_terminal(self, nonterminal, invalid_terminal):
return self._error("Invalid symbol ID: {} ({})".format(invalid_terminal.id, invalid_terminal.string))
def unrecognized_token(self, string, line, col):
lines = string.split('\n')
bad_line = lines[line-1]
return self._error('Unrecognized token on line {}, column {}:\n\n{}\n{}'.format(
line, col, bad_line, ''.join([' ' for x in range(col-1)]) + '^'
))
def missing_list_items(self, method, required, found, last):
return self._error("List for {} requires {} items but only {} were found.".format(method, required, found))
def missing_terminator(self, method, terminator, last):
return self._error("List for "+method+" is missing a terminator")
class ParserContext:
def __init__(self, tokens, errors):
self.__dict__.update(locals())
self.nonterminal_string = None
self.rule_string = None
# Parser Code #
terminals = {
0: 'else',
1: 'gteq',
2: 'not_equal',
3: 'in',
4: 'colon',
5: 'lparen',
6: 'asterisk',
7: 'object',
8: 'identifier',
9: 'null',
10: 'plus',
11: 'cmd_attr_hint',
12: 'if',
13: 'dot',
14: 'version_name',
15: 'meta_value',
16: 'double_pipe',
17: 'quote',
18: 'e',
19: 'workflow',
20: 'boolean',
21: 'call',
22: 'percent',
23: 'raw_cmd_start',
24: 'lt',
25: 'import',
26: 'output',
27: 'fqn',
28: 'as',
29: 'input',
30: 'runtime',
31: 'while',
32: 'struct',
33: 'alias',
34: 'double_ampersand',
35: 'rbrace',
36: 'expression_placeholder_end',
37: 'rparen',
38: 'double_equal',
39: 'dash',
40: 'slash',
41: 'parameter_meta',
42: 'type',
43: 'lsquare',
44: 'version',
45: 'float',
46: 'qmark',
47: 'raw_command',
48: 'task',
49: 'expression_placeholder_start',
50: 'integer',
51: 'raw_cmd_end',
52: 'lbrace',
53: 'equal',
54: 'meta',
55: 'cmd_part',
56: 'gt',
57: 'comma',
58: 'string',
59: 'then',
60: 'rsquare',
61: 'not',
62: 'type_e',
63: 'lteq',
64: 'scatter',
'else': 0,
'gteq': 1,
'not_equal': 2,
'in': 3,
'colon': 4,
'lparen': 5,
'asterisk': 6,
'object': 7,
'identifier': 8,
'null': 9,
'plus': 10,
'cmd_attr_hint': 11,
'if': 12,
'dot': 13,
'version_name': 14,
'meta_value': 15,
'double_pipe': 16,
'quote': 17,
'e': 18,
'workflow': 19,
'boolean': 20,
'call': 21,
'percent': 22,
'raw_cmd_start': 23,
'lt': 24,
'import': 25,
'output': 26,
'fqn': 27,
'as': 28,
'input': 29,
'runtime': 30,
'while': 31,
'struct': 32,
'alias': 33,
'double_ampersand': 34,
'rbrace': 35,
'expression_placeholder_end': 36,
'rparen': 37,
'double_equal': 38,
'dash': 39,
'slash': 40,
'parameter_meta': 41,
'type': 42,
'lsquare': 43,
'version': 44,
'float': 45,
'qmark': 46,
'raw_command': 47,
'task': 48,
'expression_placeholder_start': 49,
'integer': 50,
'raw_cmd_end': 51,
'lbrace': 52,
'equal': 53,
'meta': 54,
'cmd_part': 55,
'gt': 56,
'comma': 57,
'string': 58,
'then': 59,
'rsquare': 60,
'not': 61,
'type_e': 62,
'lteq': 63,
'scatter': 64,
}
# table[nonterminal][terminal] = rule
table = [
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 84, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 77, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 73, -1, -1, -1, 73, -1, -1, -1, -1, -1, -1, -1, -1, 73, -1, -1, -1, -1, 73, -1, -1, 73, -1, 73, -1, -1, -1, 73, -1, -1, -1, -1, -1, 73, 73, -1, -1, -1, -1, -1, -1, -1, -1, -1, 72, -1, 73, -1, -1, -1, -1, -1, -1, -1, 73, -1, 73],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 60, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 46, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 79, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 18, -1, -1, -1, -1, -1, 18, -1, -1, 17, -1, -1, -1, 18, 18, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 18, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 74, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 53, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, -1, -1, -1, 76, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 82, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 83, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 33, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 87, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 48, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 58, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 58, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 58, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 49, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 86, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 52, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 52, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 52, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 44, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 27, -1, -1, 26, 28, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 29, 31, -1, -1, -1, -1, 25, -1, -1, -1, -1, -1, -1, 30, -1, -1, -1, -1, -1, -1, -1, 31, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 45, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, 55, -1, 55, 55, -1, 55, -1, 55, -1, -1, -1, -1, 55, 55, -1, 55, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 55, -1, -1, -1, 55, -1, 55, -1, -1, -1, -1, 55, -1, 55, -1, -1, -1, -1, -1, -1, -1, -1, 55, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 50, -1, -1, -1, -1, -1, -1, -1, -1, 51, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 64, -1, -1, -1, -1, -1, -1, -1, -1, 61, -1, -1, -1, -1, 67, -1, -1, 66, -1, 63, -1, -1, -1, -1, -1, -1, -1, -1, -1, 68, 62, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 69, -1, -1, -1, -1, -1, -1, -1, 62, -1, 65],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 80, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 57, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, -1, -1, -1, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 85],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, 71, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, -1, -1, -1, 71, -1, 70, 71, -1, 71, -1, -1, -1, 71, -1, -1, -1, -1, -1, 71, 71, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71, -1, 71, -1, -1, -1, -1, -1, -1, -1, 71, -1, 71],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 54, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
]
nonterminal_first = {
65: [12],
66: [52],
67: [-1, 62, 8, 42],
68: [-1, 52],
69: [19],
70: [-1, 25],
71: [62, 8, 42],
72: [17],
73: [41],
74: [29],
75: [28],
76: [-1, 28],
77: [11],
78: [21],
79: [58, -1, 49],
80: [62, 8, 42],
81: [-1, 29],
82: [-1, 8],
83: [48],
84: [-1, 55, 49],
85: [5, 39, 7, 10, 8, 43, 12, 45, -1, 50, 18, 17, 20, 52, 61],
86: [-1, 8],
87: [17],
88: [-1, 62, 8, 42],
89: [5, 39, 7, 8, 10, 43, 12, 45, -1, 50, 18, 17, 20, 52, 61],
90: [54],
91: [32],
92: [31],
93: [62, 8, 42],
94: [47],
95: [-1, 62, 8, 42],
96: [8],
97: [29],
98: [-1, 62, 8, 42],
99: [52],
100: [52],
101: [62, 8, 42],
102: [8],
103: [8],
104: [19, 48, 32],
105: [-1, 8],
106: [20, 43, 45, 52, 15, 9, 50, 17],
107: [62, 8, 42],
108: [-1, 8],
109: [25],
110: [8],
111: [-1, 8],
112: [-1, 58],
113: [29, 54, 8, 41, 26, 47, 62, 30, 42],
114: [54],
115: [29, 8, 41, 12, -1, 31, 21, 54, 26, 64, 62, 42],
116: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
117: [-1, 53],
118: [21, 54, 62, 8, 41, 26, 12, 64, 31, 29, 42],
119: [49],
120: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
121: [28],
122: [44],
123: [-1, 11],
124: [9, 43, 45, -1, 15, 50, 17, 20, 52],
125: [33],
126: [49, 58],
127: [26],
128: [30],
129: [-1, 33],
130: [-1, 19, 48, 32],
131: [55, 49],
132: [64],
133: [41],
134: [-1, 28],
135: [44],
136: [47, 29, 54, 8, 41, 26, -1, 62, 30, 42],
137: [53],
}
nonterminal_follow = {
65: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
66: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
67: [60],
68: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
69: [19, -1, 48, 32],
70: [19, -1, 48, 32],
71: [42, 35, 62, 8],
72: [19, 35, 25, 48, 8, 57, 60, -1, 28, 32],
73: [35, 62, 8, 41, 47, 54, 26, 29, 30, 42],
74: [35],
75: [33, 19, 25, -1, 48, 32],
76: [33, 19, -1, 48, 25, 32],
77: [5, 39, 7, 8, 10, 43, 11, 12, 45, 50, 18, 17, 20, 52, 61],
78: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
79: [17],
80: [35, 62, 8, 41, 12, 47, 31, 21, 54, 26, 64, 29, 30, 42],
81: [35],
82: [35],
83: [19, -1, 48, 32],
84: [51],
85: [37, 60],
86: [35],
87: [1, 2, 5, 6, 7, 8, 12, 16, 17, 24, 31, 36, 35, 38, 40, 41, 45, 47, 50, 54, 56, 57, 60, 61, 62, 42, 0, 64, 4, 10, 11, 13, 18, 20, 21, 22, 26, 29, 30, 39, 37, 43, 52, 59, 34, 63],
88: [35],
89: [35],
90: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
91: [19, -1, 48, 32],
92: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
93: [57, 60, 8],
94: [35, 62, 8, 41, 47, 54, 26, 29, 30, 42],
95: [35],
96: [57, 35],
97: [35, 62, 8, 41, 12, 47, 31, 21, 54, 26, 64, 29, 30, 42],
98: [35],
99: [35, 62, 8, 41, 47, 54, 26, 29, 30, 42],
100: [35, 62, 8, 41, 12, 47, 31, 21, 54, 26, 64, 29, 30, 42],
101: [42, 35, 62, 8],
102: [57, 35, 8],
103: [57, 35],
104: [19, -1, 48, 32],
105: [35],
106: [57, 60, 35, 8],
107: [42, 35, 62, 8],
108: [35],
109: [19, -1, 48, 25, 32],
110: [35, 8],
111: [35],
112: [17],
113: [35, 62, 8, 41, 47, 54, 26, 29, 30, 42],
114: [35, 62, 8, 41, 47, 54, 26, 29, 30, 42],
115: [35],
116: [57, 35],
117: [42, 35, 62, 8],
118: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
119: [51, 58, 55, 49, 17],
120: [0, 1, 2, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 18, 17, 20, 21, 22, 64, 24, 26, 29, 34, 30, 31, 36, 39, 37, 38, 35, 40, 41, 43, 45, 47, 50, 52, 54, 56, 57, 59, 60, 61, 62, 63, 42],
121: [35, 62, 8, 41, 12, 31, 21, 52, 54, 26, 64, 29, 42],
122: [-1, 25],
123: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
124: [60],
125: [33, 19, 25, -1, 48, 32],
126: [58, 49, 17],
127: [35, 62, 8, 41, 12, 47, 31, 21, 54, 26, 64, 29, 30, 42],
128: [35, 62, 8, 41, 47, 54, 26, 29, 30, 42],
129: [19, -1, 48, 25, 32],
130: [-1],
131: [51, 55, 49],
132: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
133: [29, 35, 8, 41, 42, 12, 31, 21, 54, 26, 62, 64],
134: [35, 62, 8, 41, 12, 31, 21, 52, 54, 26, 64, 29, 42],
135: [-1],
136: [35],
137: [35, 62, 8, 41, 12, 47, 31, 21, 54, 26, 64, 29, 30, 42],
}
rule_first = {
0: [-1, 25],
1: [-1, 19, 48, 32],
2: [44],
3: [19],
4: [48],
5: [32],
6: [44],
7: [-1, 62, 8, 42],
8: [32],
9: [42, 62, 8],
10: [58],
11: [-1],
12: [17],
13: [-1, 49, 58],
14: [17],
15: [58],
16: [49],
17: [28],
18: [-1],
19: [33, -1],
20: [25],
21: [28],
22: [33],
23: [-1, 29, 54, 8, 41, 26, 47, 62, 30, 42],
24: [48],
25: [47],
26: [29],
27: [26],
28: [30],
29: [41],
30: [54],
31: [42, 62, 8],
32: [-1, 55, 49],
33: [47],
34: [55],
35: [49],
36: [-1, 11],
37: [49],
38: [11],
39: [-1, 62, 8, 42],
40: [29],
41: [30],
42: [-1, 8],
43: [52],
44: [8],
45: [54],
46: [41],
47: [-1, 8],
48: [52],
49: [8],
50: [53],
51: [-1],
52: [42, 62, 8],
53: [42, 62, 8],
54: [53],
55: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
56: [-1, 62, 8, 42],
57: [26],
58: [42, 62, 8],
59: [21, 54, 62, 8, 41, 26, 12, 64, -1, 31, 29, 42],
60: [19],
61: [21],
62: [42, 62, 8],
63: [31],
64: [12],
65: [64],
66: [29],
67: [26],
68: [41],
69: [54],
70: [28],
71: [-1],
72: [52],
73: [-1],
74: [21],
75: [29],
76: [-1],
77: [52],
78: [-1, 8],
79: [29],
80: [28],
81: [41],
82: [54],
83: [31],
84: [12],
85: [64],
86: [8],
87: [8],
88: [17],
89: [20],
90: [50],
91: [45],
92: [9],
93: [20, 52, 9, 43, 45, -1, 15, 50, 17],
94: [43],
95: [-1, 8],
96: [52],
97: [-1, 62, 8, 42],
98: [42],
99: [42],
100: [42],
101: [42],
102: [8],
103: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
104: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
105: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
106: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
107: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
108: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
109: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
110: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
111: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
112: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
113: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
114: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
115: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
116: [61],
117: [10],
118: [39],
119: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, -1, 61, 50, 18],
120: [8],
121: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
122: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, 61, 50, 18],
123: [-1, 8],
124: [7],
125: [43],
126: [20, 52, 5, 39, 7, 8, 10, 43, 17, 12, 45, -1, 61, 50, 18],
127: [52],
128: [5],
129: [12],
130: [17],
131: [8],
132: [20],
133: [50],
134: [45],
}
nonterminal_rules = {
65: [
"$if_stmt = :if :lparen $e :rparen :lbrace $_gen15 :rbrace -> If( expression=$2, body=$5 )",
],
66: [
"$call_brace_block = :lbrace $_gen18 :rbrace -> $1",
],
67: [
"$_gen22 = list($type_e, :comma)",
],
68: [
"$_gen17 = $call_brace_block",
"$_gen17 = :_empty",
],
69: [
"$workflow = :workflow :identifier :lbrace $_gen15 :rbrace -> Workflow( name=$1, body=$3 )",
],
70: [
"$_gen0 = list($import)",
],
71: [
"$struct_declaration = $type_e :identifier -> StructEntry( type=$0, name=$1 )",
],
72: [
"$static_string = :quote $_gen3 :quote -> StaticString( value=$1 )",
],
73: [
"$parameter_meta = :parameter_meta $meta_map -> ParameterMeta( map=$1 )",
],
74: [
"$call_body = :input :colon $_gen19 -> CallBody( inputs=$2 )",
],
75: [
"$import_namespace = :as :identifier -> $1",
],
76: [
"$_gen5 = $import_namespace",
"$_gen5 = :_empty",
],
77: [
"$expression_placeholder_kv = :cmd_attr_hint :identifier :equal $e -> ExpressionPlaceholderAttr( key=$1, value=$3 )",
],
78: [
"$call = :call :fqn $_gen16 $_gen17 -> Call( task=$1, alias=$2, body=$3 )",
],
79: [
"$_gen4 = list($string_piece)",
],
80: [
"$declaration = $type_e :identifier $setter -> Declaration( type=$0, name=$1, expression=$2 )",
],
81: [
"$_gen18 = $call_body",
"$_gen18 = :_empty",
],
82: [
"$_gen19 = list($input_kv, :comma)",
],
83: [
"$task = :task :identifier :lbrace $_gen7 :rbrace -> Task( name=$1, sections=$3 )",
],
84: [
"$_gen8 = list($command_part)",
],
85: [
"$_gen23 = list($e, :comma)",
],
86: [
"$_gen21 = list($meta_kv, :comma)",
],
87: [
"$string_literal = :quote $_gen4 :quote -> StringLiteral( pieces=$1 )",
],
88: [
"$_gen10 = list($input_declaration)",
],
89: [
"$_gen25 = list($map_kv, :comma)",
],
90: [
"$wf_meta = :meta $meta_map -> Meta( map=$1 )",
],
91: [
"$struct = :struct :identifier :lbrace $_gen2 :rbrace -> Struct( name=$1, entries=$3 )",
],
92: [
"$while_loop = :while :lparen $e :rparen :lbrace $_gen15 :rbrace -> WhileLoop( expression=$2, body=$5 )",
],
93: [
"$type_e = :type <=> :lsquare $_gen22 :rsquare -> Type( name=$0, subtype=$2 )",
"$type_e = :type <=> :qmark -> OptionalType( innerType=$0 )",
"$type_e = :type <=> :plus -> NonEmptyType( innerType=$0 )",
"$type_e = :type",
"$type_e = :identifier",
],
94: [
"$command = :raw_command :raw_cmd_start $_gen8 :raw_cmd_end -> RawCommand( parts=$2 )",
],
95: [
"$_gen14 = list($output_kv)",
],
96: [
"$input_kv = :identifier :equal $e -> ObjectKV( key=$0, value=$2 )",
],
97: [
"$inputs = :input :lbrace $_gen10 :rbrace -> Inputs( inputs=$2 )",
],
98: [
"$_gen2 = list($struct_declaration)",
],
99: [
"$rt_map = :lbrace $_gen11 :rbrace -> $1",
],
100: [
"$meta_map = :lbrace $_gen12 :rbrace -> $1",
],
101: [
"$output_kv = $type_e :identifier :equal $e -> Output( type=$0, name=$1, expression=$3 )",
],
102: [
"$meta_kv = :identifier :colon $meta_value -> MetaKvPair( key=$0, value=$2 )",
],
103: [
"$object_kv = :identifier :colon $e -> ObjectKV( key=$0, value=$2 )",
],
104: [
"$file_body_element = $workflow",
"$file_body_element = $task",
"$file_body_element = $struct",
],
105: [
"$_gen11 = list($kv)",
],
106: [
"$meta_value = $static_string",
"$meta_value = :boolean",
"$meta_value = :integer",
"$meta_value = :float",
"$meta_value = :null",
"$meta_value = :lsquare $_gen20 :rsquare -> MetaArray( values=$1 )",
"$meta_value = :lbrace $_gen21 :rbrace -> MetaObject( map=$1 )",
],
107: [
"$input_declaration = $type_e :identifier $_gen13 -> InputDeclaration( type=$0, name=$1, expression=$2 )",
],
108: [
"$_gen12 = list($meta_kv)",
],
109: [
"$import = :import $static_string $_gen5 $_gen6 -> Import( uri=$1, namespace=$2, aliases=$3 )",
],
110: [
"$kv = :identifier :colon $e -> RuntimeAttribute( key=$0, value=$2 )",
],
111: [
"$_gen24 = list($object_kv, :comma)",
],
112: [
"$_gen3 = :string",
"$_gen3 = :_empty",
],
113: [
"$task_sections = $command",
"$task_sections = $inputs",
"$task_sections = $outputs",
"$task_sections = $runtime",
"$task_sections = $parameter_meta",
"$task_sections = $meta",
"$task_sections = $declaration",
],
114: [
"$meta = :meta $meta_map -> Meta( map=$1 )",
],
115: [
"$_gen15 = list($wf_body_element)",
],
116: [
"$map_kv = $e :colon $e -> MapLiteralKv( key=$0, value=$2 )",
],
117: [
"$_gen13 = $setter",
"$_gen13 = :_empty",
],
118: [
"$wf_body_element = $call",
"$wf_body_element = $declaration",
"$wf_body_element = $while_loop",
"$wf_body_element = $if_stmt",
"$wf_body_element = $scatter",
"$wf_body_element = $inputs",
"$wf_body_element = $outputs",
"$wf_body_element = $wf_parameter_meta",
"$wf_body_element = $wf_meta",
],
119: [
"$expression_placeholder = :expression_placeholder_start $_gen9 $e :expression_placeholder_end -> ExpressionPlaceholder( attributes=$1, expr=$2 )",
],
120: [
"$e = $e :double_pipe $e -> LogicalOr( lhs=$0, rhs=$2 )",
"$e = $e :double_ampersand $e -> LogicalAnd( lhs=$0, rhs=$2 )",
"$e = $e :double_equal $e -> Equals( lhs=$0, rhs=$2 )",
"$e = $e :not_equal $e -> NotEquals( lhs=$0, rhs=$2 )",
"$e = $e :lt $e -> LessThan( lhs=$0, rhs=$2 )",
"$e = $e :lteq $e -> LessThanOrEqual( lhs=$0, rhs=$2 )",
"$e = $e :gt $e -> GreaterThan( lhs=$0, rhs=$2 )",
"$e = $e :gteq $e -> GreaterThanOrEqual( lhs=$0, rhs=$2 )",
"$e = $e :plus $e -> Add( lhs=$0, rhs=$2 )",
"$e = $e :dash $e -> Subtract( lhs=$0, rhs=$2 )",
"$e = $e :asterisk $e -> Multiply( lhs=$0, rhs=$2 )",
"$e = $e :slash $e -> Divide( lhs=$0, rhs=$2 )",
"$e = $e :percent $e -> Remainder( lhs=$0, rhs=$2 )",
"$e = :not $e -> LogicalNot( expression=$1 )",
"$e = :plus $e -> UnaryPlus( expression=$1 )",
"$e = :dash $e -> UnaryNegation( expression=$1 )",
"$e = :identifier <=> :lparen $_gen23 :rparen -> FunctionCall( name=$0, params=$2 )",
"$e = $e <=> :lsquare $e :rsquare -> ArrayOrMapLookup( lhs=$0, rhs=$2 )",
"$e = $e <=> :dot :identifier -> MemberAccess( value=$0, member=$2 )",
"$e = :object :lbrace $_gen24 :rbrace -> ObjectLiteral( map=$2 )",
"$e = :lsquare $_gen23 :rsquare -> ArrayLiteral( values=$1 )",
"$e = :lbrace $_gen25 :rbrace -> MapLiteral( map=$1 )",
"$e = :lparen $_gen23 :rparen -> TupleLiteral( values=$1 )",
"$e = :if $e :then $e :else $e -> TernaryIf( cond=$1, iftrue=$3, iffalse=$5 )",
"$e = $string_literal",
"$e = :identifier",
"$e = :boolean",
"$e = :integer",
"$e = :float",
],
121: [
"$alias = :as :identifier -> $1",
],
122: [
"$version = :version :version_name -> VersionDeclaration( v=$1 )",
],
123: [
"$_gen9 = list($expression_placeholder_kv)",
],
124: [
"$_gen20 = list($meta_value, :comma)",
],
125: [
"$import_alias = :alias :identifier :as :identifier -> ImportAlias( old_name=$1, new_name=$3 )",
],
126: [
"$string_piece = :string",
"$string_piece = $expression_placeholder",
],
127: [
"$outputs = :output :lbrace $_gen14 :rbrace -> Outputs( outputs=$2 )",
],
128: [
"$runtime = :runtime $rt_map -> Runtime( map=$1 )",
],
129: [
"$_gen6 = list($import_alias)",
],
130: [
"$_gen1 = list($file_body_element)",
],
131: [
"$command_part = :cmd_part",
"$command_part = $expression_placeholder",
],
132: [
"$scatter = :scatter :lparen :identifier :in $e :rparen :lbrace $_gen15 :rbrace -> Scatter( item=$2, collection=$4, body=$7 )",
],
133: [
"$wf_parameter_meta = :parameter_meta $meta_map -> ParameterMeta( map=$1 )",
],
134: [
"$_gen16 = $alias",
"$_gen16 = :_empty",
],
135: [
"$document = $version $_gen0 $_gen1 -> Draft3File( version=$0, imports=$1, body=$2 )",
],
136: [
"$_gen7 = list($task_sections)",
],
137: [
"$setter = :equal $e -> $1",
],
}
rules = {
0: "$_gen0 = list($import)",
1: "$_gen1 = list($file_body_element)",
2: "$document = $version $_gen0 $_gen1 -> Draft3File( version=$0, imports=$1, body=$2 )",
3: "$file_body_element = $workflow",
4: "$file_body_element = $task",
5: "$file_body_element = $struct",
6: "$version = :version :version_name -> VersionDeclaration( v=$1 )",
7: "$_gen2 = list($struct_declaration)",
8: "$struct = :struct :identifier :lbrace $_gen2 :rbrace -> Struct( name=$1, entries=$3 )",
9: "$struct_declaration = $type_e :identifier -> StructEntry( type=$0, name=$1 )",
10: "$_gen3 = :string",
11: "$_gen3 = :_empty",
12: "$static_string = :quote $_gen3 :quote -> StaticString( value=$1 )",
13: "$_gen4 = list($string_piece)",
14: "$string_literal = :quote $_gen4 :quote -> StringLiteral( pieces=$1 )",
15: "$string_piece = :string",
16: "$string_piece = $expression_placeholder",
17: "$_gen5 = $import_namespace",
18: "$_gen5 = :_empty",
19: "$_gen6 = list($import_alias)",
20: "$import = :import $static_string $_gen5 $_gen6 -> Import( uri=$1, namespace=$2, aliases=$3 )",
21: "$import_namespace = :as :identifier -> $1",
22: "$import_alias = :alias :identifier :as :identifier -> ImportAlias( old_name=$1, new_name=$3 )",
23: "$_gen7 = list($task_sections)",
24: "$task = :task :identifier :lbrace $_gen7 :rbrace -> Task( name=$1, sections=$3 )",
25: "$task_sections = $command",
26: "$task_sections = $inputs",
27: "$task_sections = $outputs",
28: "$task_sections = $runtime",
29: "$task_sections = $parameter_meta",
30: "$task_sections = $meta",
31: "$task_sections = $declaration",
32: "$_gen8 = list($command_part)",
33: "$command = :raw_command :raw_cmd_start $_gen8 :raw_cmd_end -> RawCommand( parts=$2 )",
34: "$command_part = :cmd_part",
35: "$command_part = $expression_placeholder",
36: "$_gen9 = list($expression_placeholder_kv)",
37: "$expression_placeholder = :expression_placeholder_start $_gen9 $e :expression_placeholder_end -> ExpressionPlaceholder( attributes=$1, expr=$2 )",
38: "$expression_placeholder_kv = :cmd_attr_hint :identifier :equal $e -> ExpressionPlaceholderAttr( key=$1, value=$3 )",
39: "$_gen10 = list($input_declaration)",
40: "$inputs = :input :lbrace $_gen10 :rbrace -> Inputs( inputs=$2 )",
41: "$runtime = :runtime $rt_map -> Runtime( map=$1 )",
42: "$_gen11 = list($kv)",
43: "$rt_map = :lbrace $_gen11 :rbrace -> $1",
44: "$kv = :identifier :colon $e -> RuntimeAttribute( key=$0, value=$2 )",
45: "$meta = :meta $meta_map -> Meta( map=$1 )",
46: "$parameter_meta = :parameter_meta $meta_map -> ParameterMeta( map=$1 )",
47: "$_gen12 = list($meta_kv)",
48: "$meta_map = :lbrace $_gen12 :rbrace -> $1",
49: "$meta_kv = :identifier :colon $meta_value -> MetaKvPair( key=$0, value=$2 )",
50: "$_gen13 = $setter",
51: "$_gen13 = :_empty",
52: "$input_declaration = $type_e :identifier $_gen13 -> InputDeclaration( type=$0, name=$1, expression=$2 )",
53: "$declaration = $type_e :identifier $setter -> Declaration( type=$0, name=$1, expression=$2 )",
54: "$setter = :equal $e -> $1",
55: "$map_kv = $e :colon $e -> MapLiteralKv( key=$0, value=$2 )",
56: "$_gen14 = list($output_kv)",
57: "$outputs = :output :lbrace $_gen14 :rbrace -> Outputs( outputs=$2 )",
58: "$output_kv = $type_e :identifier :equal $e -> Output( type=$0, name=$1, expression=$3 )",
59: "$_gen15 = list($wf_body_element)",
60: "$workflow = :workflow :identifier :lbrace $_gen15 :rbrace -> Workflow( name=$1, body=$3 )",
61: "$wf_body_element = $call",
62: "$wf_body_element = $declaration",
63: "$wf_body_element = $while_loop",
64: "$wf_body_element = $if_stmt",
65: "$wf_body_element = $scatter",
66: "$wf_body_element = $inputs",
67: "$wf_body_element = $outputs",
68: "$wf_body_element = $wf_parameter_meta",
69: "$wf_body_element = $wf_meta",
70: "$_gen16 = $alias",
71: "$_gen16 = :_empty",
72: "$_gen17 = $call_brace_block",
73: "$_gen17 = :_empty",
74: "$call = :call :fqn $_gen16 $_gen17 -> Call( task=$1, alias=$2, body=$3 )",
75: "$_gen18 = $call_body",
76: "$_gen18 = :_empty",
77: "$call_brace_block = :lbrace $_gen18 :rbrace -> $1",
78: "$_gen19 = list($input_kv, :comma)",
79: "$call_body = :input :colon $_gen19 -> CallBody( inputs=$2 )",
80: "$alias = :as :identifier -> $1",
81: "$wf_parameter_meta = :parameter_meta $meta_map -> ParameterMeta( map=$1 )",
82: "$wf_meta = :meta $meta_map -> Meta( map=$1 )",
83: "$while_loop = :while :lparen $e :rparen :lbrace $_gen15 :rbrace -> WhileLoop( expression=$2, body=$5 )",
84: "$if_stmt = :if :lparen $e :rparen :lbrace $_gen15 :rbrace -> If( expression=$2, body=$5 )",
85: "$scatter = :scatter :lparen :identifier :in $e :rparen :lbrace $_gen15 :rbrace -> Scatter( item=$2, collection=$4, body=$7 )",
86: "$object_kv = :identifier :colon $e -> ObjectKV( key=$0, value=$2 )",
87: "$input_kv = :identifier :equal $e -> ObjectKV( key=$0, value=$2 )",
88: "$meta_value = $static_string",
89: "$meta_value = :boolean",
90: "$meta_value = :integer",
91: "$meta_value = :float",
92: "$meta_value = :null",
93: "$_gen20 = list($meta_value, :comma)",
94: "$meta_value = :lsquare $_gen20 :rsquare -> MetaArray( values=$1 )",
95: "$_gen21 = list($meta_kv, :comma)",
96: "$meta_value = :lbrace $_gen21 :rbrace -> MetaObject( map=$1 )",
97: "$_gen22 = list($type_e, :comma)",
98: "$type_e = :type <=> :lsquare $_gen22 :rsquare -> Type( name=$0, subtype=$2 )",
99: "$type_e = :type <=> :qmark -> OptionalType( innerType=$0 )",
100: "$type_e = :type <=> :plus -> NonEmptyType( innerType=$0 )",
101: "$type_e = :type",
102: "$type_e = :identifier",
103: "$e = $e :double_pipe $e -> LogicalOr( lhs=$0, rhs=$2 )",
104: "$e = $e :double_ampersand $e -> LogicalAnd( lhs=$0, rhs=$2 )",
105: "$e = $e :double_equal $e -> Equals( lhs=$0, rhs=$2 )",
106: "$e = $e :not_equal $e -> NotEquals( lhs=$0, rhs=$2 )",
107: "$e = $e :lt $e -> LessThan( lhs=$0, rhs=$2 )",
108: "$e = $e :lteq $e -> LessThanOrEqual( lhs=$0, rhs=$2 )",
109: "$e = $e :gt $e -> GreaterThan( lhs=$0, rhs=$2 )",
110: "$e = $e :gteq $e -> GreaterThanOrEqual( lhs=$0, rhs=$2 )",
111: "$e = $e :plus $e -> Add( lhs=$0, rhs=$2 )",
112: "$e = $e :dash $e -> Subtract( lhs=$0, rhs=$2 )",
113: "$e = $e :asterisk $e -> Multiply( lhs=$0, rhs=$2 )",
114: "$e = $e :slash $e -> Divide( lhs=$0, rhs=$2 )",
115: "$e = $e :percent $e -> Remainder( lhs=$0, rhs=$2 )",
116: "$e = :not $e -> LogicalNot( expression=$1 )",
117: "$e = :plus $e -> UnaryPlus( expression=$1 )",
118: "$e = :dash $e -> UnaryNegation( expression=$1 )",
119: "$_gen23 = list($e, :comma)",
120: "$e = :identifier <=> :lparen $_gen23 :rparen -> FunctionCall( name=$0, params=$2 )",
121: "$e = $e <=> :lsquare $e :rsquare -> ArrayOrMapLookup( lhs=$0, rhs=$2 )",
122: "$e = $e <=> :dot :identifier -> MemberAccess( value=$0, member=$2 )",
123: "$_gen24 = list($object_kv, :comma)",
124: "$e = :object :lbrace $_gen24 :rbrace -> ObjectLiteral( map=$2 )",
125: "$e = :lsquare $_gen23 :rsquare -> ArrayLiteral( values=$1 )",
126: "$_gen25 = list($map_kv, :comma)",
127: "$e = :lbrace $_gen25 :rbrace -> MapLiteral( map=$1 )",
128: "$e = :lparen $_gen23 :rparen -> TupleLiteral( values=$1 )",
129: "$e = :if $e :then $e :else $e -> TernaryIf( cond=$1, iftrue=$3, iffalse=$5 )",
130: "$e = $string_literal",
131: "$e = :identifier",
132: "$e = :boolean",
133: "$e = :integer",
134: "$e = :float",
}
def is_terminal(id): return isinstance(id, int) and 0 <= id <= 64
def parse(tokens, errors=None, start=None):
if errors is None:
errors = DefaultSyntaxErrorHandler()
if isinstance(tokens, str):
tokens = lex(tokens, 'string', errors)
ctx = ParserContext(tokens, errors)
tree = parse_document(ctx)
if tokens.current() != None:
raise ctx.errors.excess_tokens()
return tree
def expect(ctx, terminal_id):
current = ctx.tokens.current()
if not current:
raise ctx.errors.no_more_tokens(ctx.nonterminal, terminals[terminal_id], ctx.tokens.last())
if current.id != terminal_id:
raise ctx.errors.unexpected_symbol(ctx.nonterminal, current, [terminals[terminal_id]], ctx.rule)
next = ctx.tokens.advance()
if next and not is_terminal(next.id):
raise ctx.errors.invalid_terminal(ctx.nonterminal, next)
return current
# START definitions for expression parser: e
infix_binding_power_e = {
16: 4000, # $e = $e :double_pipe $e -> LogicalOr( lhs=$0, rhs=$2 )
34: 5000, # $e = $e :double_ampersand $e -> LogicalAnd( lhs=$0, rhs=$2 )
38: 6000, # $e = $e :double_equal $e -> Equals( lhs=$0, rhs=$2 )
2: 6000, # $e = $e :not_equal $e -> NotEquals( lhs=$0, rhs=$2 )
24: 7000, # $e = $e :lt $e -> LessThan( lhs=$0, rhs=$2 )
63: 7000, # $e = $e :lteq $e -> LessThanOrEqual( lhs=$0, rhs=$2 )
56: 7000, # $e = $e :gt $e -> GreaterThan( lhs=$0, rhs=$2 )
1: 7000, # $e = $e :gteq $e -> GreaterThanOrEqual( lhs=$0, rhs=$2 )
10: 8000, # $e = $e :plus $e -> Add( lhs=$0, rhs=$2 )
39: 8000, # $e = $e :dash $e -> Subtract( lhs=$0, rhs=$2 )
6: 9000, # $e = $e :asterisk $e -> Multiply( lhs=$0, rhs=$2 )
40: 9000, # $e = $e :slash $e -> Divide( lhs=$0, rhs=$2 )
22: 9000, # $e = $e :percent $e -> Remainder( lhs=$0, rhs=$2 )
5: 11000, # $e = :identifier <=> :lparen list($e, :comma) :rparen -> FunctionCall( name=$0, params=$2 )
43: 12000, # $e = $e <=> :lsquare $e :rsquare -> ArrayOrMapLookup( lhs=$0, rhs=$2 )
13: 13000, # $e = $e <=> :dot :identifier -> MemberAccess( value=$0, member=$2 )
}
prefix_binding_power_e = {
61: 10000, # $e = :not $e -> LogicalNot( expression=$1 )
10: 10000, # $e = :plus $e -> UnaryPlus( expression=$1 )
39: 10000, # $e = :dash $e -> UnaryNegation( expression=$1 )
}
def get_infix_binding_power_e(terminal_id):
try:
return infix_binding_power_e[terminal_id]
except:
return 0
def get_prefix_binding_power_e(terminal_id):
try:
return prefix_binding_power_e[terminal_id]
except:
return 0
def parse_e(ctx):
return parse_e_internal(ctx, rbp=0)
def parse_e_internal(ctx, rbp=0):
left = nud_e(ctx)
if isinstance(left, ParseTree):
left.isExpr = True
left.isNud = True
while ctx.tokens.current() and rbp < get_infix_binding_power_e(ctx.tokens.current().id):
left = led_e(left, ctx)
if left:
left.isExpr = True
return left
def nud_e(ctx):
tree = ParseTree(NonTerminal(120, 'e'))
current = ctx.tokens.current()
ctx.nonterminal = "e"
if not current:
return tree
elif current.id in rule_first[116]:
# rule first == not
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :not $e -> LogicalNot( expression=$1 )
ctx.rule = rules[116]
ast_parameters = OrderedDict([
('expression', 1),
])
tree.astTransform = AstTransformNodeCreator('LogicalNot', ast_parameters)
tree.nudMorphemeCount = 2
tree.add(expect(ctx, 61))
tree.add(parse_e_internal(ctx, get_prefix_binding_power_e(61)))
tree.isPrefix = True
elif current.id in rule_first[117]:
# rule first == plus
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :plus $e -> UnaryPlus( expression=$1 )
ctx.rule = rules[117]
ast_parameters = OrderedDict([
('expression', 1),
])
tree.astTransform = AstTransformNodeCreator('UnaryPlus', ast_parameters)
tree.nudMorphemeCount = 2
tree.add(expect(ctx, 10))
tree.add(parse_e_internal(ctx, get_prefix_binding_power_e(10)))
tree.isPrefix = True
elif current.id in rule_first[118]:
# rule first == dash
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :dash $e -> UnaryNegation( expression=$1 )
ctx.rule = rules[118]
ast_parameters = OrderedDict([
('expression', 1),
])
tree.astTransform = AstTransformNodeCreator('UnaryNegation', ast_parameters)
tree.nudMorphemeCount = 2
tree.add(expect(ctx, 39))
tree.add(parse_e_internal(ctx, get_prefix_binding_power_e(39)))
tree.isPrefix = True
elif current.id in rule_first[120]:
# rule first == identifier
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :identifier <=> :lparen $_gen23 :rparen -> FunctionCall( name=$0, params=$2 )
ctx.rule = rules[120]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 8))
elif current.id in rule_first[124]:
# rule first == object
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :object :lbrace $_gen24 :rbrace -> ObjectLiteral( map=$2 )
ctx.rule = rules[124]
ast_parameters = OrderedDict([
('map', 2),
])
tree.astTransform = AstTransformNodeCreator('ObjectLiteral', ast_parameters)
tree.nudMorphemeCount = 4
tree.add(expect(ctx, 7))
tree.add(expect(ctx, 52))
tree.add(parse__gen24(ctx))
tree.add(expect(ctx, 35))
elif current.id in rule_first[125]:
# rule first == lsquare
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :lsquare $_gen23 :rsquare -> ArrayLiteral( values=$1 )
ctx.rule = rules[125]
ast_parameters = OrderedDict([
('values', 1),
])
tree.astTransform = AstTransformNodeCreator('ArrayLiteral', ast_parameters)
tree.nudMorphemeCount = 3
tree.add(expect(ctx, 43))
tree.add(parse__gen23(ctx))
tree.add(expect(ctx, 60))
elif current.id in rule_first[127]:
# rule first == lbrace
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :lbrace $_gen25 :rbrace -> MapLiteral( map=$1 )
ctx.rule = rules[127]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('MapLiteral', ast_parameters)
tree.nudMorphemeCount = 3
tree.add(expect(ctx, 52))
tree.add(parse__gen25(ctx))
tree.add(expect(ctx, 35))
elif current.id in rule_first[128]:
# rule first == lparen
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :lparen $_gen23 :rparen -> TupleLiteral( values=$1 )
ctx.rule = rules[128]
ast_parameters = OrderedDict([
('values', 1),
])
tree.astTransform = AstTransformNodeCreator('TupleLiteral', ast_parameters)
tree.nudMorphemeCount = 3
tree.add(expect(ctx, 5))
tree.add(parse__gen23(ctx))
tree.add(expect(ctx, 37))
elif current.id in rule_first[129]:
# rule first == if
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :if $e :then $e :else $e -> TernaryIf( cond=$1, iftrue=$3, iffalse=$5 )
ctx.rule = rules[129]
ast_parameters = OrderedDict([
('cond', 1),
('iftrue', 3),
('iffalse', 5),
])
tree.astTransform = AstTransformNodeCreator('TernaryIf', ast_parameters)
tree.nudMorphemeCount = 6
tree.add(expect(ctx, 12))
tree.add(parse_e(ctx))
tree.add(expect(ctx, 59))
tree.add(parse_e(ctx))
tree.add(expect(ctx, 0))
tree.add(parse_e(ctx))
elif current.id in rule_first[130]:
# rule first == quote
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = $string_literal
ctx.rule = rules[130]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(parse_string_literal(ctx))
elif current.id in rule_first[131]:
# rule first == identifier
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :identifier
ctx.rule = rules[131]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 8))
elif current.id in rule_first[132]:
# rule first == boolean
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :boolean
ctx.rule = rules[132]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 20))
elif current.id in rule_first[133]:
# rule first == integer
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :integer
ctx.rule = rules[133]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 50))
elif current.id in rule_first[134]:
# rule first == float
# e first == boolean, lbrace, lparen, dash, object, identifier, plus, lsquare, quote, if, float, not, integer, e
# $e = :float
ctx.rule = rules[134]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 45))
return tree
def led_e(left, ctx):
tree = ParseTree(NonTerminal(120, 'e'))
current = ctx.tokens.current()
ctx.nonterminal = "e"
if current.id == 16: # :double_pipe
# $e = $e :double_pipe $e -> LogicalOr( lhs=$0, rhs=$2 )
ctx.rule = rules[103]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('LogicalOr', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 16)) # :double_pipe
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(16) - modifier))
if current.id == 34: # :double_ampersand
# $e = $e :double_ampersand $e -> LogicalAnd( lhs=$0, rhs=$2 )
ctx.rule = rules[104]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('LogicalAnd', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 34)) # :double_ampersand
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(34) - modifier))
if current.id == 38: # :double_equal
# $e = $e :double_equal $e -> Equals( lhs=$0, rhs=$2 )
ctx.rule = rules[105]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('Equals', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 38)) # :double_equal
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(38) - modifier))
if current.id == 2: # :not_equal
# $e = $e :not_equal $e -> NotEquals( lhs=$0, rhs=$2 )
ctx.rule = rules[106]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('NotEquals', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 2)) # :not_equal
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(2) - modifier))
if current.id == 24: # :lt
# $e = $e :lt $e -> LessThan( lhs=$0, rhs=$2 )
ctx.rule = rules[107]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('LessThan', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 24)) # :lt
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(24) - modifier))
if current.id == 63: # :lteq
# $e = $e :lteq $e -> LessThanOrEqual( lhs=$0, rhs=$2 )
ctx.rule = rules[108]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('LessThanOrEqual', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 63)) # :lteq
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(63) - modifier))
if current.id == 56: # :gt
# $e = $e :gt $e -> GreaterThan( lhs=$0, rhs=$2 )
ctx.rule = rules[109]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('GreaterThan', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 56)) # :gt
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(56) - modifier))
if current.id == 1: # :gteq
# $e = $e :gteq $e -> GreaterThanOrEqual( lhs=$0, rhs=$2 )
ctx.rule = rules[110]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('GreaterThanOrEqual', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 1)) # :gteq
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(1) - modifier))
if current.id == 10: # :plus
# $e = $e :plus $e -> Add( lhs=$0, rhs=$2 )
ctx.rule = rules[111]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('Add', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 10)) # :plus
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(10) - modifier))
if current.id == 39: # :dash
# $e = $e :dash $e -> Subtract( lhs=$0, rhs=$2 )
ctx.rule = rules[112]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('Subtract', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 39)) # :dash
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(39) - modifier))
if current.id == 6: # :asterisk
# $e = $e :asterisk $e -> Multiply( lhs=$0, rhs=$2 )
ctx.rule = rules[113]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('Multiply', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 6)) # :asterisk
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(6) - modifier))
if current.id == 40: # :slash
# $e = $e :slash $e -> Divide( lhs=$0, rhs=$2 )
ctx.rule = rules[114]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('Divide', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 40)) # :slash
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(40) - modifier))
if current.id == 22: # :percent
# $e = $e :percent $e -> Remainder( lhs=$0, rhs=$2 )
ctx.rule = rules[115]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('Remainder', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 22)) # :percent
modifier = 0
tree.isInfix = True
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(22) - modifier))
if current.id == 5: # :lparen
# $e = :identifier <=> :lparen $_gen23 :rparen -> FunctionCall( name=$0, params=$2 )
ctx.rule = rules[120]
ast_parameters = OrderedDict([
('name', 0),
('params', 2),
])
tree.astTransform = AstTransformNodeCreator('FunctionCall', ast_parameters)
tree.add(left)
tree.add(expect(ctx, 5)) # :lparen
tree.add(parse__gen23(ctx))
tree.add(expect(ctx, 37)) # :rparen
if current.id == 43: # :lsquare
# $e = $e <=> :lsquare $e :rsquare -> ArrayOrMapLookup( lhs=$0, rhs=$2 )
ctx.rule = rules[121]
ast_parameters = OrderedDict([
('lhs', 0),
('rhs', 2),
])
tree.astTransform = AstTransformNodeCreator('ArrayOrMapLookup', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 43)) # :lsquare
modifier = 0
tree.add(parse_e_internal(ctx, get_infix_binding_power_e(43) - modifier))
tree.add(expect(ctx, 60)) # :rsquare
if current.id == 13: # :dot
# $e = $e <=> :dot :identifier -> MemberAccess( value=$0, member=$2 )
ctx.rule = rules[122]
ast_parameters = OrderedDict([
('value', 0),
('member', 2),
])
tree.astTransform = AstTransformNodeCreator('MemberAccess', ast_parameters)
tree.isExprNud = True
tree.add(left)
tree.add(expect(ctx, 13)) # :dot
tree.add(expect(ctx, 8)) # :identifier
return tree
# END definitions for expression parser: e
# START definitions for expression parser: meta_value
infix_binding_power_meta_value = {
}
prefix_binding_power_meta_value = {
}
def get_infix_binding_power_meta_value(terminal_id):
try:
return infix_binding_power_meta_value[terminal_id]
except:
return 0
def get_prefix_binding_power_meta_value(terminal_id):
try:
return prefix_binding_power_meta_value[terminal_id]
except:
return 0
def parse_meta_value(ctx):
return parse_meta_value_internal(ctx, rbp=0)
def parse_meta_value_internal(ctx, rbp=0):
left = nud_meta_value(ctx)
if isinstance(left, ParseTree):
left.isExpr = True
left.isNud = True
while ctx.tokens.current() and rbp < get_infix_binding_power_meta_value(ctx.tokens.current().id):
left = led_meta_value(left, ctx)
if left:
left.isExpr = True
return left
def nud_meta_value(ctx):
tree = ParseTree(NonTerminal(106, 'meta_value'))
current = ctx.tokens.current()
ctx.nonterminal = "meta_value"
if not current:
return tree
if current.id in rule_first[88]:
# rule first == quote
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = $static_string
ctx.rule = rules[88]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(parse_static_string(ctx))
elif current.id in rule_first[89]:
# rule first == boolean
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = :boolean
ctx.rule = rules[89]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 20))
elif current.id in rule_first[90]:
# rule first == integer
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = :integer
ctx.rule = rules[90]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 50))
elif current.id in rule_first[91]:
# rule first == float
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = :float
ctx.rule = rules[91]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 45))
elif current.id in rule_first[92]:
# rule first == null
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = :null
ctx.rule = rules[92]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 9))
elif current.id in rule_first[94]:
# rule first == lsquare
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = :lsquare $_gen20 :rsquare -> MetaArray( values=$1 )
ctx.rule = rules[94]
ast_parameters = OrderedDict([
('values', 1),
])
tree.astTransform = AstTransformNodeCreator('MetaArray', ast_parameters)
tree.nudMorphemeCount = 3
tree.add(expect(ctx, 43))
tree.add(parse__gen20(ctx))
tree.add(expect(ctx, 60))
elif current.id in rule_first[96]:
# rule first == lbrace
# e first == boolean, lsquare, float, lbrace, meta_value, null, integer, quote
# $meta_value = :lbrace $_gen21 :rbrace -> MetaObject( map=$1 )
ctx.rule = rules[96]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('MetaObject', ast_parameters)
tree.nudMorphemeCount = 3
tree.add(expect(ctx, 52))
tree.add(parse__gen21(ctx))
tree.add(expect(ctx, 35))
return tree
def led_meta_value(left, ctx):
tree = ParseTree(NonTerminal(106, 'meta_value'))
current = ctx.tokens.current()
ctx.nonterminal = "meta_value"
return tree
# END definitions for expression parser: meta_value
# START definitions for expression parser: type_e
infix_binding_power_type_e = {
43: 1000, # $type_e = :type <=> :lsquare list($type_e, :comma) :rsquare -> Type( name=$0, subtype=$2 )
46: 2000, # $type_e = :type <=> :qmark -> OptionalType( innerType=$0 )
10: 3000, # $type_e = :type <=> :plus -> NonEmptyType( innerType=$0 )
}
prefix_binding_power_type_e = {
}
def get_infix_binding_power_type_e(terminal_id):
try:
return infix_binding_power_type_e[terminal_id]
except:
return 0
def get_prefix_binding_power_type_e(terminal_id):
try:
return prefix_binding_power_type_e[terminal_id]
except:
return 0
def parse_type_e(ctx):
return parse_type_e_internal(ctx, rbp=0)
def parse_type_e_internal(ctx, rbp=0):
left = nud_type_e(ctx)
if isinstance(left, ParseTree):
left.isExpr = True
left.isNud = True
while ctx.tokens.current() and rbp < get_infix_binding_power_type_e(ctx.tokens.current().id):
left = led_type_e(left, ctx)
if left:
left.isExpr = True
return left
def nud_type_e(ctx):
tree = ParseTree(NonTerminal(93, 'type_e'))
current = ctx.tokens.current()
ctx.nonterminal = "type_e"
if not current:
return tree
if current.id in rule_first[98]:
# rule first == type
# e first == type_e, identifier, type
# $type_e = :type <=> :lsquare $_gen22 :rsquare -> Type( name=$0, subtype=$2 )
ctx.rule = rules[98]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 42))
elif current.id in rule_first[99]:
# rule first == type
# e first == type_e, identifier, type
# $type_e = :type <=> :qmark -> OptionalType( innerType=$0 )
ctx.rule = rules[99]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 42))
elif current.id in rule_first[100]:
# rule first == type
# e first == type_e, identifier, type
# $type_e = :type <=> :plus -> NonEmptyType( innerType=$0 )
ctx.rule = rules[100]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 42))
elif current.id in rule_first[101]:
# rule first == type
# e first == type_e, identifier, type
# $type_e = :type
ctx.rule = rules[101]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 42))
elif current.id in rule_first[102]:
# rule first == identifier
# e first == type_e, identifier, type
# $type_e = :identifier
ctx.rule = rules[102]
tree.astTransform = AstTransformSubstitution(0)
tree.nudMorphemeCount = 1
tree.add(expect(ctx, 8))
return tree
def led_type_e(left, ctx):
tree = ParseTree(NonTerminal(93, 'type_e'))
current = ctx.tokens.current()
ctx.nonterminal = "type_e"
if current.id == 43: # :lsquare
# $type_e = :type <=> :lsquare $_gen22 :rsquare -> Type( name=$0, subtype=$2 )
ctx.rule = rules[98]
ast_parameters = OrderedDict([
('name', 0),
('subtype', 2),
])
tree.astTransform = AstTransformNodeCreator('Type', ast_parameters)
tree.add(left)
tree.add(expect(ctx, 43)) # :lsquare
tree.add(parse__gen22(ctx))
tree.add(expect(ctx, 60)) # :rsquare
if current.id == 46: # :qmark
# $type_e = :type <=> :qmark -> OptionalType( innerType=$0 )
ctx.rule = rules[99]
ast_parameters = OrderedDict([
('innerType', 0),
])
tree.astTransform = AstTransformNodeCreator('OptionalType', ast_parameters)
tree.add(left)
tree.add(expect(ctx, 46)) # :qmark
if current.id == 10: # :plus
# $type_e = :type <=> :plus -> NonEmptyType( innerType=$0 )
ctx.rule = rules[100]
ast_parameters = OrderedDict([
('innerType', 0),
])
tree.astTransform = AstTransformNodeCreator('NonEmptyType', ast_parameters)
tree.add(left)
tree.add(expect(ctx, 10)) # :plus
return tree
# END definitions for expression parser: type_e
def parse__gen0(ctx):
tree = ParseTree(NonTerminal(70, '_gen0'))
tree.list = True
ctx.nonterminal = "_gen0"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[70] and \
ctx.tokens.current().id in nonterminal_follow[70]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(70)):
tree.add(parse_import(ctx))
ctx.nonterminal = "_gen0" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen1(ctx):
tree = ParseTree(NonTerminal(130, '_gen1'))
tree.list = True
ctx.nonterminal = "_gen1"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[130] and \
ctx.tokens.current().id in nonterminal_follow[130]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(130)):
tree.add(parse_file_body_element(ctx))
ctx.nonterminal = "_gen1" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen10(ctx):
tree = ParseTree(NonTerminal(88, '_gen10'))
tree.list = True
ctx.nonterminal = "_gen10"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[88] and \
ctx.tokens.current().id in nonterminal_follow[88]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(88)):
tree.add(parse_input_declaration(ctx))
ctx.nonterminal = "_gen10" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen11(ctx):
tree = ParseTree(NonTerminal(105, '_gen11'))
tree.list = True
ctx.nonterminal = "_gen11"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[105] and \
ctx.tokens.current().id in nonterminal_follow[105]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(105)):
tree.add(parse_kv(ctx))
ctx.nonterminal = "_gen11" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen12(ctx):
tree = ParseTree(NonTerminal(108, '_gen12'))
tree.list = True
ctx.nonterminal = "_gen12"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[108] and \
ctx.tokens.current().id in nonterminal_follow[108]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(108)):
tree.add(parse_meta_kv(ctx))
ctx.nonterminal = "_gen12" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen14(ctx):
tree = ParseTree(NonTerminal(95, '_gen14'))
tree.list = True
ctx.nonterminal = "_gen14"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[95] and \
ctx.tokens.current().id in nonterminal_follow[95]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(95)):
tree.add(parse_output_kv(ctx))
ctx.nonterminal = "_gen14" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen15(ctx):
tree = ParseTree(NonTerminal(115, '_gen15'))
tree.list = True
ctx.nonterminal = "_gen15"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[115] and \
ctx.tokens.current().id in nonterminal_follow[115]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(115)):
tree.add(parse_wf_body_element(ctx))
ctx.nonterminal = "_gen15" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen19(ctx):
tree = ParseTree(NonTerminal(82, '_gen19'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen19"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[82] and \
ctx.tokens.current().id in nonterminal_follow[82]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(82)):
tree.add(parse_input_kv(ctx))
ctx.nonterminal = "_gen19" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen2(ctx):
tree = ParseTree(NonTerminal(98, '_gen2'))
tree.list = True
ctx.nonterminal = "_gen2"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[98] and \
ctx.tokens.current().id in nonterminal_follow[98]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(98)):
tree.add(parse_struct_declaration(ctx))
ctx.nonterminal = "_gen2" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen20(ctx):
tree = ParseTree(NonTerminal(124, '_gen20'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen20"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[124] and \
ctx.tokens.current().id in nonterminal_follow[124]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(124)):
tree.add(parse_meta_value(ctx))
ctx.nonterminal = "_gen20" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen21(ctx):
tree = ParseTree(NonTerminal(86, '_gen21'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen21"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[86] and \
ctx.tokens.current().id in nonterminal_follow[86]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(86)):
tree.add(parse_meta_kv(ctx))
ctx.nonterminal = "_gen21" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen22(ctx):
tree = ParseTree(NonTerminal(67, '_gen22'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen22"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[67] and \
ctx.tokens.current().id in nonterminal_follow[67]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(67)):
tree.add(parse_type_e(ctx))
ctx.nonterminal = "_gen22" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen23(ctx):
tree = ParseTree(NonTerminal(85, '_gen23'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen23"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[85] and \
ctx.tokens.current().id in nonterminal_follow[85]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(85)):
tree.add(parse_e(ctx))
ctx.nonterminal = "_gen23" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen24(ctx):
tree = ParseTree(NonTerminal(111, '_gen24'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen24"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[111] and \
ctx.tokens.current().id in nonterminal_follow[111]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(111)):
tree.add(parse_object_kv(ctx))
ctx.nonterminal = "_gen24" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen25(ctx):
tree = ParseTree(NonTerminal(89, '_gen25'))
tree.list = True
tree.list_separator_id = 57
ctx.nonterminal = "_gen25"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[89] and \
ctx.tokens.current().id in nonterminal_follow[89]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(89)):
tree.add(parse_map_kv(ctx))
ctx.nonterminal = "_gen25" # Horrible -- because parse_* can reset this
if ctx.tokens.current() is not None and ctx.tokens.current().id == 57:
tree.add(expect(ctx, 57));
else:
break
minimum = max(minimum - 1, 0)
return tree
def parse__gen4(ctx):
tree = ParseTree(NonTerminal(79, '_gen4'))
tree.list = True
ctx.nonterminal = "_gen4"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[79] and \
ctx.tokens.current().id in nonterminal_follow[79]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(79)):
tree.add(parse_string_piece(ctx))
ctx.nonterminal = "_gen4" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen6(ctx):
tree = ParseTree(NonTerminal(129, '_gen6'))
tree.list = True
ctx.nonterminal = "_gen6"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[129] and \
ctx.tokens.current().id in nonterminal_follow[129]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(129)):
tree.add(parse_import_alias(ctx))
ctx.nonterminal = "_gen6" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen7(ctx):
tree = ParseTree(NonTerminal(136, '_gen7'))
tree.list = True
ctx.nonterminal = "_gen7"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[136] and \
ctx.tokens.current().id in nonterminal_follow[136]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(136)):
tree.add(parse_task_sections(ctx))
ctx.nonterminal = "_gen7" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen8(ctx):
tree = ParseTree(NonTerminal(84, '_gen8'))
tree.list = True
ctx.nonterminal = "_gen8"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[84] and \
ctx.tokens.current().id in nonterminal_follow[84]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(84)):
tree.add(parse_command_part(ctx))
ctx.nonterminal = "_gen8" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen9(ctx):
tree = ParseTree(NonTerminal(123, '_gen9'))
tree.list = True
ctx.nonterminal = "_gen9"
if ctx.tokens.current() is not None and \
ctx.tokens.current().id not in nonterminal_first[123] and \
ctx.tokens.current().id in nonterminal_follow[123]:
return tree
if ctx.tokens.current() is None:
return tree
minimum = 0
while minimum > 0 or \
(ctx.tokens.current() is not None and \
ctx.tokens.current().id in nonterminal_first.get(123)):
tree.add(parse_expression_placeholder_kv(ctx))
ctx.nonterminal = "_gen9" # Horrible -- because parse_* can reset this
minimum = max(minimum - 1, 0)
return tree
def parse__gen13(ctx):
current = ctx.tokens.current()
rule = table[52][current.id] if current else -1
tree = ParseTree(NonTerminal(117, '_gen13'))
ctx.nonterminal = "_gen13"
if current != None and current.id in nonterminal_follow[117] and current.id not in nonterminal_first[117]:
return tree
if current == None:
return tree
if rule == 50: # $_gen13 = $setter
ctx.rule = rules[50]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_setter(ctx)
tree.add(subtree)
return tree
return tree
def parse__gen16(ctx):
current = ctx.tokens.current()
rule = table[69][current.id] if current else -1
tree = ParseTree(NonTerminal(134, '_gen16'))
ctx.nonterminal = "_gen16"
if current != None and current.id in nonterminal_follow[134] and current.id not in nonterminal_first[134]:
return tree
if current == None:
return tree
if rule == 70: # $_gen16 = $alias
ctx.rule = rules[70]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_alias(ctx)
tree.add(subtree)
return tree
return tree
def parse__gen17(ctx):
current = ctx.tokens.current()
rule = table[3][current.id] if current else -1
tree = ParseTree(NonTerminal(68, '_gen17'))
ctx.nonterminal = "_gen17"
if current != None and current.id in nonterminal_follow[68] and current.id not in nonterminal_first[68]:
return tree
if current == None:
return tree
if rule == 72: # $_gen17 = $call_brace_block
ctx.rule = rules[72]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_call_brace_block(ctx)
tree.add(subtree)
return tree
return tree
def parse__gen18(ctx):
current = ctx.tokens.current()
rule = table[16][current.id] if current else -1
tree = ParseTree(NonTerminal(81, '_gen18'))
ctx.nonterminal = "_gen18"
if current != None and current.id in nonterminal_follow[81] and current.id not in nonterminal_first[81]:
return tree
if current == None:
return tree
if rule == 75: # $_gen18 = $call_body
ctx.rule = rules[75]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_call_body(ctx)
tree.add(subtree)
return tree
return tree
def parse__gen3(ctx):
current = ctx.tokens.current()
rule = table[47][current.id] if current else -1
tree = ParseTree(NonTerminal(112, '_gen3'))
ctx.nonterminal = "_gen3"
if current != None and current.id in nonterminal_follow[112] and current.id not in nonterminal_first[112]:
return tree
if current == None:
return tree
if rule == 10: # $_gen3 = :string
ctx.rule = rules[10]
tree.astTransform = AstTransformSubstitution(0)
t = expect(ctx, 58) # :string
tree.add(t)
return tree
return tree
def parse__gen5(ctx):
current = ctx.tokens.current()
rule = table[11][current.id] if current else -1
tree = ParseTree(NonTerminal(76, '_gen5'))
ctx.nonterminal = "_gen5"
if current != None and current.id in nonterminal_follow[76] and current.id not in nonterminal_first[76]:
return tree
if current == None:
return tree
if rule == 17: # $_gen5 = $import_namespace
ctx.rule = rules[17]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_import_namespace(ctx)
tree.add(subtree)
return tree
return tree
def parse_alias(ctx):
current = ctx.tokens.current()
rule = table[56][current.id] if current else -1
tree = ParseTree(NonTerminal(121, 'alias'))
ctx.nonterminal = "alias"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 80: # $alias = :as :identifier -> $1
ctx.rule = rules[80]
tree.astTransform = AstTransformSubstitution(1)
t = expect(ctx, 28) # :as
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[121] if x >=0],
rules[80]
)
def parse_call(ctx):
current = ctx.tokens.current()
rule = table[13][current.id] if current else -1
tree = ParseTree(NonTerminal(78, 'call'))
ctx.nonterminal = "call"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 74: # $call = :call :fqn $_gen16 $_gen17 -> Call( task=$1, alias=$2, body=$3 )
ctx.rule = rules[74]
ast_parameters = OrderedDict([
('task', 1),
('alias', 2),
('body', 3),
])
tree.astTransform = AstTransformNodeCreator('Call', ast_parameters)
t = expect(ctx, 21) # :call
tree.add(t)
t = expect(ctx, 27) # :fqn
tree.add(t)
subtree = parse__gen16(ctx)
tree.add(subtree)
subtree = parse__gen17(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[78] if x >=0],
rules[74]
)
def parse_call_body(ctx):
current = ctx.tokens.current()
rule = table[9][current.id] if current else -1
tree = ParseTree(NonTerminal(74, 'call_body'))
ctx.nonterminal = "call_body"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 79: # $call_body = :input :colon $_gen19 -> CallBody( inputs=$2 )
ctx.rule = rules[79]
ast_parameters = OrderedDict([
('inputs', 2),
])
tree.astTransform = AstTransformNodeCreator('CallBody', ast_parameters)
t = expect(ctx, 29) # :input
tree.add(t)
t = expect(ctx, 4) # :colon
tree.add(t)
subtree = parse__gen19(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[74] if x >=0],
rules[79]
)
def parse_call_brace_block(ctx):
current = ctx.tokens.current()
rule = table[1][current.id] if current else -1
tree = ParseTree(NonTerminal(66, 'call_brace_block'))
ctx.nonterminal = "call_brace_block"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 77: # $call_brace_block = :lbrace $_gen18 :rbrace -> $1
ctx.rule = rules[77]
tree.astTransform = AstTransformSubstitution(1)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen18(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[66] if x >=0],
rules[77]
)
def parse_command(ctx):
current = ctx.tokens.current()
rule = table[29][current.id] if current else -1
tree = ParseTree(NonTerminal(94, 'command'))
ctx.nonterminal = "command"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 33: # $command = :raw_command :raw_cmd_start $_gen8 :raw_cmd_end -> RawCommand( parts=$2 )
ctx.rule = rules[33]
ast_parameters = OrderedDict([
('parts', 2),
])
tree.astTransform = AstTransformNodeCreator('RawCommand', ast_parameters)
t = expect(ctx, 47) # :raw_command
tree.add(t)
t = expect(ctx, 23) # :raw_cmd_start
tree.add(t)
subtree = parse__gen8(ctx)
tree.add(subtree)
t = expect(ctx, 51) # :raw_cmd_end
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[94] if x >=0],
rules[33]
)
def parse_command_part(ctx):
current = ctx.tokens.current()
rule = table[66][current.id] if current else -1
tree = ParseTree(NonTerminal(131, 'command_part'))
ctx.nonterminal = "command_part"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 34: # $command_part = :cmd_part
ctx.rule = rules[34]
tree.astTransform = AstTransformSubstitution(0)
t = expect(ctx, 55) # :cmd_part
tree.add(t)
return tree
elif rule == 35: # $command_part = $expression_placeholder
ctx.rule = rules[35]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_expression_placeholder(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[131] if x >=0],
rules[35]
)
def parse_declaration(ctx):
current = ctx.tokens.current()
rule = table[15][current.id] if current else -1
tree = ParseTree(NonTerminal(80, 'declaration'))
ctx.nonterminal = "declaration"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 53: # $declaration = $type_e :identifier $setter -> Declaration( type=$0, name=$1, expression=$2 )
ctx.rule = rules[53]
ast_parameters = OrderedDict([
('type', 0),
('name', 1),
('expression', 2),
])
tree.astTransform = AstTransformNodeCreator('Declaration', ast_parameters)
subtree = parse_type_e(ctx)
tree.add(subtree)
t = expect(ctx, 8) # :identifier
tree.add(t)
subtree = parse_setter(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[80] if x >=0],
rules[53]
)
def parse_document(ctx):
current = ctx.tokens.current()
rule = table[70][current.id] if current else -1
tree = ParseTree(NonTerminal(135, 'document'))
ctx.nonterminal = "document"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 2: # $document = $version $_gen0 $_gen1 -> Draft3File( version=$0, imports=$1, body=$2 )
ctx.rule = rules[2]
ast_parameters = OrderedDict([
('version', 0),
('imports', 1),
('body', 2),
])
tree.astTransform = AstTransformNodeCreator('Draft3File', ast_parameters)
subtree = parse_version(ctx)
tree.add(subtree)
subtree = parse__gen0(ctx)
tree.add(subtree)
subtree = parse__gen1(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[135] if x >=0],
rules[2]
)
def parse_expression_placeholder(ctx):
current = ctx.tokens.current()
rule = table[54][current.id] if current else -1
tree = ParseTree(NonTerminal(119, 'expression_placeholder'))
ctx.nonterminal = "expression_placeholder"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 37: # $expression_placeholder = :expression_placeholder_start $_gen9 $e :expression_placeholder_end -> ExpressionPlaceholder( attributes=$1, expr=$2 )
ctx.rule = rules[37]
ast_parameters = OrderedDict([
('attributes', 1),
('expr', 2),
])
tree.astTransform = AstTransformNodeCreator('ExpressionPlaceholder', ast_parameters)
t = expect(ctx, 49) # :expression_placeholder_start
tree.add(t)
subtree = parse__gen9(ctx)
tree.add(subtree)
subtree = parse_e(ctx)
tree.add(subtree)
t = expect(ctx, 36) # :expression_placeholder_end
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[119] if x >=0],
rules[37]
)
def parse_expression_placeholder_kv(ctx):
current = ctx.tokens.current()
rule = table[12][current.id] if current else -1
tree = ParseTree(NonTerminal(77, 'expression_placeholder_kv'))
ctx.nonterminal = "expression_placeholder_kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 38: # $expression_placeholder_kv = :cmd_attr_hint :identifier :equal $e -> ExpressionPlaceholderAttr( key=$1, value=$3 )
ctx.rule = rules[38]
ast_parameters = OrderedDict([
('key', 1),
('value', 3),
])
tree.astTransform = AstTransformNodeCreator('ExpressionPlaceholderAttr', ast_parameters)
t = expect(ctx, 11) # :cmd_attr_hint
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 53) # :equal
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[77] if x >=0],
rules[38]
)
def parse_file_body_element(ctx):
current = ctx.tokens.current()
rule = table[39][current.id] if current else -1
tree = ParseTree(NonTerminal(104, 'file_body_element'))
ctx.nonterminal = "file_body_element"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 3: # $file_body_element = $workflow
ctx.rule = rules[3]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_workflow(ctx)
tree.add(subtree)
return tree
elif rule == 4: # $file_body_element = $task
ctx.rule = rules[4]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_task(ctx)
tree.add(subtree)
return tree
elif rule == 5: # $file_body_element = $struct
ctx.rule = rules[5]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_struct(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[104] if x >=0],
rules[5]
)
def parse_if_stmt(ctx):
current = ctx.tokens.current()
rule = table[0][current.id] if current else -1
tree = ParseTree(NonTerminal(65, 'if_stmt'))
ctx.nonterminal = "if_stmt"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 84: # $if_stmt = :if :lparen $e :rparen :lbrace $_gen15 :rbrace -> If( expression=$2, body=$5 )
ctx.rule = rules[84]
ast_parameters = OrderedDict([
('expression', 2),
('body', 5),
])
tree.astTransform = AstTransformNodeCreator('If', ast_parameters)
t = expect(ctx, 12) # :if
tree.add(t)
t = expect(ctx, 5) # :lparen
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
t = expect(ctx, 37) # :rparen
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen15(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[65] if x >=0],
rules[84]
)
def parse_import(ctx):
current = ctx.tokens.current()
rule = table[44][current.id] if current else -1
tree = ParseTree(NonTerminal(109, 'import'))
ctx.nonterminal = "import"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 20: # $import = :import $static_string $_gen5 $_gen6 -> Import( uri=$1, namespace=$2, aliases=$3 )
ctx.rule = rules[20]
ast_parameters = OrderedDict([
('uri', 1),
('namespace', 2),
('aliases', 3),
])
tree.astTransform = AstTransformNodeCreator('Import', ast_parameters)
t = expect(ctx, 25) # :import
tree.add(t)
subtree = parse_static_string(ctx)
tree.add(subtree)
subtree = parse__gen5(ctx)
tree.add(subtree)
subtree = parse__gen6(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[109] if x >=0],
rules[20]
)
def parse_import_alias(ctx):
current = ctx.tokens.current()
rule = table[60][current.id] if current else -1
tree = ParseTree(NonTerminal(125, 'import_alias'))
ctx.nonterminal = "import_alias"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 22: # $import_alias = :alias :identifier :as :identifier -> ImportAlias( old_name=$1, new_name=$3 )
ctx.rule = rules[22]
ast_parameters = OrderedDict([
('old_name', 1),
('new_name', 3),
])
tree.astTransform = AstTransformNodeCreator('ImportAlias', ast_parameters)
t = expect(ctx, 33) # :alias
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 28) # :as
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[125] if x >=0],
rules[22]
)
def parse_import_namespace(ctx):
current = ctx.tokens.current()
rule = table[10][current.id] if current else -1
tree = ParseTree(NonTerminal(75, 'import_namespace'))
ctx.nonterminal = "import_namespace"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 21: # $import_namespace = :as :identifier -> $1
ctx.rule = rules[21]
tree.astTransform = AstTransformSubstitution(1)
t = expect(ctx, 28) # :as
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[75] if x >=0],
rules[21]
)
def parse_input_declaration(ctx):
current = ctx.tokens.current()
rule = table[42][current.id] if current else -1
tree = ParseTree(NonTerminal(107, 'input_declaration'))
ctx.nonterminal = "input_declaration"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 52: # $input_declaration = $type_e :identifier $_gen13 -> InputDeclaration( type=$0, name=$1, expression=$2 )
ctx.rule = rules[52]
ast_parameters = OrderedDict([
('type', 0),
('name', 1),
('expression', 2),
])
tree.astTransform = AstTransformNodeCreator('InputDeclaration', ast_parameters)
subtree = parse_type_e(ctx)
tree.add(subtree)
t = expect(ctx, 8) # :identifier
tree.add(t)
subtree = parse__gen13(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[107] if x >=0],
rules[52]
)
def parse_input_kv(ctx):
current = ctx.tokens.current()
rule = table[31][current.id] if current else -1
tree = ParseTree(NonTerminal(96, 'input_kv'))
ctx.nonterminal = "input_kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 87: # $input_kv = :identifier :equal $e -> ObjectKV( key=$0, value=$2 )
ctx.rule = rules[87]
ast_parameters = OrderedDict([
('key', 0),
('value', 2),
])
tree.astTransform = AstTransformNodeCreator('ObjectKV', ast_parameters)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 53) # :equal
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[96] if x >=0],
rules[87]
)
def parse_inputs(ctx):
current = ctx.tokens.current()
rule = table[32][current.id] if current else -1
tree = ParseTree(NonTerminal(97, 'inputs'))
ctx.nonterminal = "inputs"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 40: # $inputs = :input :lbrace $_gen10 :rbrace -> Inputs( inputs=$2 )
ctx.rule = rules[40]
ast_parameters = OrderedDict([
('inputs', 2),
])
tree.astTransform = AstTransformNodeCreator('Inputs', ast_parameters)
t = expect(ctx, 29) # :input
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen10(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[97] if x >=0],
rules[40]
)
def parse_kv(ctx):
current = ctx.tokens.current()
rule = table[45][current.id] if current else -1
tree = ParseTree(NonTerminal(110, 'kv'))
ctx.nonterminal = "kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 44: # $kv = :identifier :colon $e -> RuntimeAttribute( key=$0, value=$2 )
ctx.rule = rules[44]
ast_parameters = OrderedDict([
('key', 0),
('value', 2),
])
tree.astTransform = AstTransformNodeCreator('RuntimeAttribute', ast_parameters)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 4) # :colon
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[110] if x >=0],
rules[44]
)
def parse_map_kv(ctx):
current = ctx.tokens.current()
rule = table[51][current.id] if current else -1
tree = ParseTree(NonTerminal(116, 'map_kv'))
ctx.nonterminal = "map_kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 55: # $map_kv = $e :colon $e -> MapLiteralKv( key=$0, value=$2 )
ctx.rule = rules[55]
ast_parameters = OrderedDict([
('key', 0),
('value', 2),
])
tree.astTransform = AstTransformNodeCreator('MapLiteralKv', ast_parameters)
subtree = parse_e(ctx)
tree.add(subtree)
t = expect(ctx, 4) # :colon
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[116] if x >=0],
rules[55]
)
def parse_meta(ctx):
current = ctx.tokens.current()
rule = table[49][current.id] if current else -1
tree = ParseTree(NonTerminal(114, 'meta'))
ctx.nonterminal = "meta"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 45: # $meta = :meta $meta_map -> Meta( map=$1 )
ctx.rule = rules[45]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('Meta', ast_parameters)
t = expect(ctx, 54) # :meta
tree.add(t)
subtree = parse_meta_map(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[114] if x >=0],
rules[45]
)
def parse_meta_kv(ctx):
current = ctx.tokens.current()
rule = table[37][current.id] if current else -1
tree = ParseTree(NonTerminal(102, 'meta_kv'))
ctx.nonterminal = "meta_kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 49: # $meta_kv = :identifier :colon $meta_value -> MetaKvPair( key=$0, value=$2 )
ctx.rule = rules[49]
ast_parameters = OrderedDict([
('key', 0),
('value', 2),
])
tree.astTransform = AstTransformNodeCreator('MetaKvPair', ast_parameters)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 4) # :colon
tree.add(t)
subtree = parse_meta_value(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[102] if x >=0],
rules[49]
)
def parse_meta_map(ctx):
current = ctx.tokens.current()
rule = table[35][current.id] if current else -1
tree = ParseTree(NonTerminal(100, 'meta_map'))
ctx.nonterminal = "meta_map"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 48: # $meta_map = :lbrace $_gen12 :rbrace -> $1
ctx.rule = rules[48]
tree.astTransform = AstTransformSubstitution(1)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen12(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[100] if x >=0],
rules[48]
)
def parse_object_kv(ctx):
current = ctx.tokens.current()
rule = table[38][current.id] if current else -1
tree = ParseTree(NonTerminal(103, 'object_kv'))
ctx.nonterminal = "object_kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 86: # $object_kv = :identifier :colon $e -> ObjectKV( key=$0, value=$2 )
ctx.rule = rules[86]
ast_parameters = OrderedDict([
('key', 0),
('value', 2),
])
tree.astTransform = AstTransformNodeCreator('ObjectKV', ast_parameters)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 4) # :colon
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[103] if x >=0],
rules[86]
)
def parse_output_kv(ctx):
current = ctx.tokens.current()
rule = table[36][current.id] if current else -1
tree = ParseTree(NonTerminal(101, 'output_kv'))
ctx.nonterminal = "output_kv"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 58: # $output_kv = $type_e :identifier :equal $e -> Output( type=$0, name=$1, expression=$3 )
ctx.rule = rules[58]
ast_parameters = OrderedDict([
('type', 0),
('name', 1),
('expression', 3),
])
tree.astTransform = AstTransformNodeCreator('Output', ast_parameters)
subtree = parse_type_e(ctx)
tree.add(subtree)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 53) # :equal
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[101] if x >=0],
rules[58]
)
def parse_outputs(ctx):
current = ctx.tokens.current()
rule = table[62][current.id] if current else -1
tree = ParseTree(NonTerminal(127, 'outputs'))
ctx.nonterminal = "outputs"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 57: # $outputs = :output :lbrace $_gen14 :rbrace -> Outputs( outputs=$2 )
ctx.rule = rules[57]
ast_parameters = OrderedDict([
('outputs', 2),
])
tree.astTransform = AstTransformNodeCreator('Outputs', ast_parameters)
t = expect(ctx, 26) # :output
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen14(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[127] if x >=0],
rules[57]
)
def parse_parameter_meta(ctx):
current = ctx.tokens.current()
rule = table[8][current.id] if current else -1
tree = ParseTree(NonTerminal(73, 'parameter_meta'))
ctx.nonterminal = "parameter_meta"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 46: # $parameter_meta = :parameter_meta $meta_map -> ParameterMeta( map=$1 )
ctx.rule = rules[46]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('ParameterMeta', ast_parameters)
t = expect(ctx, 41) # :parameter_meta
tree.add(t)
subtree = parse_meta_map(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[73] if x >=0],
rules[46]
)
def parse_rt_map(ctx):
current = ctx.tokens.current()
rule = table[34][current.id] if current else -1
tree = ParseTree(NonTerminal(99, 'rt_map'))
ctx.nonterminal = "rt_map"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 43: # $rt_map = :lbrace $_gen11 :rbrace -> $1
ctx.rule = rules[43]
tree.astTransform = AstTransformSubstitution(1)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen11(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[99] if x >=0],
rules[43]
)
def parse_runtime(ctx):
current = ctx.tokens.current()
rule = table[63][current.id] if current else -1
tree = ParseTree(NonTerminal(128, 'runtime'))
ctx.nonterminal = "runtime"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 41: # $runtime = :runtime $rt_map -> Runtime( map=$1 )
ctx.rule = rules[41]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('Runtime', ast_parameters)
t = expect(ctx, 30) # :runtime
tree.add(t)
subtree = parse_rt_map(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[128] if x >=0],
rules[41]
)
def parse_scatter(ctx):
current = ctx.tokens.current()
rule = table[67][current.id] if current else -1
tree = ParseTree(NonTerminal(132, 'scatter'))
ctx.nonterminal = "scatter"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 85: # $scatter = :scatter :lparen :identifier :in $e :rparen :lbrace $_gen15 :rbrace -> Scatter( item=$2, collection=$4, body=$7 )
ctx.rule = rules[85]
ast_parameters = OrderedDict([
('item', 2),
('collection', 4),
('body', 7),
])
tree.astTransform = AstTransformNodeCreator('Scatter', ast_parameters)
t = expect(ctx, 64) # :scatter
tree.add(t)
t = expect(ctx, 5) # :lparen
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 3) # :in
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
t = expect(ctx, 37) # :rparen
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen15(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[132] if x >=0],
rules[85]
)
def parse_setter(ctx):
current = ctx.tokens.current()
rule = table[72][current.id] if current else -1
tree = ParseTree(NonTerminal(137, 'setter'))
ctx.nonterminal = "setter"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 54: # $setter = :equal $e -> $1
ctx.rule = rules[54]
tree.astTransform = AstTransformSubstitution(1)
t = expect(ctx, 53) # :equal
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[137] if x >=0],
rules[54]
)
def parse_static_string(ctx):
current = ctx.tokens.current()
rule = table[7][current.id] if current else -1
tree = ParseTree(NonTerminal(72, 'static_string'))
ctx.nonterminal = "static_string"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 12: # $static_string = :quote $_gen3 :quote -> StaticString( value=$1 )
ctx.rule = rules[12]
ast_parameters = OrderedDict([
('value', 1),
])
tree.astTransform = AstTransformNodeCreator('StaticString', ast_parameters)
t = expect(ctx, 17) # :quote
tree.add(t)
subtree = parse__gen3(ctx)
tree.add(subtree)
t = expect(ctx, 17) # :quote
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[72] if x >=0],
rules[12]
)
def parse_string_literal(ctx):
current = ctx.tokens.current()
rule = table[22][current.id] if current else -1
tree = ParseTree(NonTerminal(87, 'string_literal'))
ctx.nonterminal = "string_literal"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 14: # $string_literal = :quote $_gen4 :quote -> StringLiteral( pieces=$1 )
ctx.rule = rules[14]
ast_parameters = OrderedDict([
('pieces', 1),
])
tree.astTransform = AstTransformNodeCreator('StringLiteral', ast_parameters)
t = expect(ctx, 17) # :quote
tree.add(t)
subtree = parse__gen4(ctx)
tree.add(subtree)
t = expect(ctx, 17) # :quote
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[87] if x >=0],
rules[14]
)
def parse_string_piece(ctx):
current = ctx.tokens.current()
rule = table[61][current.id] if current else -1
tree = ParseTree(NonTerminal(126, 'string_piece'))
ctx.nonterminal = "string_piece"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 15: # $string_piece = :string
ctx.rule = rules[15]
tree.astTransform = AstTransformSubstitution(0)
t = expect(ctx, 58) # :string
tree.add(t)
return tree
elif rule == 16: # $string_piece = $expression_placeholder
ctx.rule = rules[16]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_expression_placeholder(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[126] if x >=0],
rules[16]
)
def parse_struct(ctx):
current = ctx.tokens.current()
rule = table[26][current.id] if current else -1
tree = ParseTree(NonTerminal(91, 'struct'))
ctx.nonterminal = "struct"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 8: # $struct = :struct :identifier :lbrace $_gen2 :rbrace -> Struct( name=$1, entries=$3 )
ctx.rule = rules[8]
ast_parameters = OrderedDict([
('name', 1),
('entries', 3),
])
tree.astTransform = AstTransformNodeCreator('Struct', ast_parameters)
t = expect(ctx, 32) # :struct
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen2(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[91] if x >=0],
rules[8]
)
def parse_struct_declaration(ctx):
current = ctx.tokens.current()
rule = table[6][current.id] if current else -1
tree = ParseTree(NonTerminal(71, 'struct_declaration'))
ctx.nonterminal = "struct_declaration"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 9: # $struct_declaration = $type_e :identifier -> StructEntry( type=$0, name=$1 )
ctx.rule = rules[9]
ast_parameters = OrderedDict([
('type', 0),
('name', 1),
])
tree.astTransform = AstTransformNodeCreator('StructEntry', ast_parameters)
subtree = parse_type_e(ctx)
tree.add(subtree)
t = expect(ctx, 8) # :identifier
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[71] if x >=0],
rules[9]
)
def parse_task(ctx):
current = ctx.tokens.current()
rule = table[18][current.id] if current else -1
tree = ParseTree(NonTerminal(83, 'task'))
ctx.nonterminal = "task"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 24: # $task = :task :identifier :lbrace $_gen7 :rbrace -> Task( name=$1, sections=$3 )
ctx.rule = rules[24]
ast_parameters = OrderedDict([
('name', 1),
('sections', 3),
])
tree.astTransform = AstTransformNodeCreator('Task', ast_parameters)
t = expect(ctx, 48) # :task
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen7(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[83] if x >=0],
rules[24]
)
def parse_task_sections(ctx):
current = ctx.tokens.current()
rule = table[48][current.id] if current else -1
tree = ParseTree(NonTerminal(113, 'task_sections'))
ctx.nonterminal = "task_sections"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 25: # $task_sections = $command
ctx.rule = rules[25]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_command(ctx)
tree.add(subtree)
return tree
elif rule == 26: # $task_sections = $inputs
ctx.rule = rules[26]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_inputs(ctx)
tree.add(subtree)
return tree
elif rule == 27: # $task_sections = $outputs
ctx.rule = rules[27]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_outputs(ctx)
tree.add(subtree)
return tree
elif rule == 28: # $task_sections = $runtime
ctx.rule = rules[28]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_runtime(ctx)
tree.add(subtree)
return tree
elif rule == 29: # $task_sections = $parameter_meta
ctx.rule = rules[29]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_parameter_meta(ctx)
tree.add(subtree)
return tree
elif rule == 30: # $task_sections = $meta
ctx.rule = rules[30]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_meta(ctx)
tree.add(subtree)
return tree
elif rule == 31: # $task_sections = $declaration
ctx.rule = rules[31]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_declaration(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[113] if x >=0],
rules[31]
)
def parse_version(ctx):
current = ctx.tokens.current()
rule = table[57][current.id] if current else -1
tree = ParseTree(NonTerminal(122, 'version'))
ctx.nonterminal = "version"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 6: # $version = :version :version_name -> VersionDeclaration( v=$1 )
ctx.rule = rules[6]
ast_parameters = OrderedDict([
('v', 1),
])
tree.astTransform = AstTransformNodeCreator('VersionDeclaration', ast_parameters)
t = expect(ctx, 44) # :version
tree.add(t)
t = expect(ctx, 14) # :version_name
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[122] if x >=0],
rules[6]
)
def parse_wf_body_element(ctx):
current = ctx.tokens.current()
rule = table[53][current.id] if current else -1
tree = ParseTree(NonTerminal(118, 'wf_body_element'))
ctx.nonterminal = "wf_body_element"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 61: # $wf_body_element = $call
ctx.rule = rules[61]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_call(ctx)
tree.add(subtree)
return tree
elif rule == 62: # $wf_body_element = $declaration
ctx.rule = rules[62]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_declaration(ctx)
tree.add(subtree)
return tree
elif rule == 63: # $wf_body_element = $while_loop
ctx.rule = rules[63]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_while_loop(ctx)
tree.add(subtree)
return tree
elif rule == 64: # $wf_body_element = $if_stmt
ctx.rule = rules[64]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_if_stmt(ctx)
tree.add(subtree)
return tree
elif rule == 65: # $wf_body_element = $scatter
ctx.rule = rules[65]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_scatter(ctx)
tree.add(subtree)
return tree
elif rule == 66: # $wf_body_element = $inputs
ctx.rule = rules[66]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_inputs(ctx)
tree.add(subtree)
return tree
elif rule == 67: # $wf_body_element = $outputs
ctx.rule = rules[67]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_outputs(ctx)
tree.add(subtree)
return tree
elif rule == 68: # $wf_body_element = $wf_parameter_meta
ctx.rule = rules[68]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_wf_parameter_meta(ctx)
tree.add(subtree)
return tree
elif rule == 69: # $wf_body_element = $wf_meta
ctx.rule = rules[69]
tree.astTransform = AstTransformSubstitution(0)
subtree = parse_wf_meta(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[118] if x >=0],
rules[69]
)
def parse_wf_meta(ctx):
current = ctx.tokens.current()
rule = table[25][current.id] if current else -1
tree = ParseTree(NonTerminal(90, 'wf_meta'))
ctx.nonterminal = "wf_meta"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 82: # $wf_meta = :meta $meta_map -> Meta( map=$1 )
ctx.rule = rules[82]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('Meta', ast_parameters)
t = expect(ctx, 54) # :meta
tree.add(t)
subtree = parse_meta_map(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[90] if x >=0],
rules[82]
)
def parse_wf_parameter_meta(ctx):
current = ctx.tokens.current()
rule = table[68][current.id] if current else -1
tree = ParseTree(NonTerminal(133, 'wf_parameter_meta'))
ctx.nonterminal = "wf_parameter_meta"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 81: # $wf_parameter_meta = :parameter_meta $meta_map -> ParameterMeta( map=$1 )
ctx.rule = rules[81]
ast_parameters = OrderedDict([
('map', 1),
])
tree.astTransform = AstTransformNodeCreator('ParameterMeta', ast_parameters)
t = expect(ctx, 41) # :parameter_meta
tree.add(t)
subtree = parse_meta_map(ctx)
tree.add(subtree)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[133] if x >=0],
rules[81]
)
def parse_while_loop(ctx):
current = ctx.tokens.current()
rule = table[27][current.id] if current else -1
tree = ParseTree(NonTerminal(92, 'while_loop'))
ctx.nonterminal = "while_loop"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 83: # $while_loop = :while :lparen $e :rparen :lbrace $_gen15 :rbrace -> WhileLoop( expression=$2, body=$5 )
ctx.rule = rules[83]
ast_parameters = OrderedDict([
('expression', 2),
('body', 5),
])
tree.astTransform = AstTransformNodeCreator('WhileLoop', ast_parameters)
t = expect(ctx, 31) # :while
tree.add(t)
t = expect(ctx, 5) # :lparen
tree.add(t)
subtree = parse_e(ctx)
tree.add(subtree)
t = expect(ctx, 37) # :rparen
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen15(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[92] if x >=0],
rules[83]
)
def parse_workflow(ctx):
current = ctx.tokens.current()
rule = table[4][current.id] if current else -1
tree = ParseTree(NonTerminal(69, 'workflow'))
ctx.nonterminal = "workflow"
if current == None:
raise ctx.errors.unexpected_eof()
if rule == 60: # $workflow = :workflow :identifier :lbrace $_gen15 :rbrace -> Workflow( name=$1, body=$3 )
ctx.rule = rules[60]
ast_parameters = OrderedDict([
('name', 1),
('body', 3),
])
tree.astTransform = AstTransformNodeCreator('Workflow', ast_parameters)
t = expect(ctx, 19) # :workflow
tree.add(t)
t = expect(ctx, 8) # :identifier
tree.add(t)
t = expect(ctx, 52) # :lbrace
tree.add(t)
subtree = parse__gen15(ctx)
tree.add(subtree)
t = expect(ctx, 35) # :rbrace
tree.add(t)
return tree
raise ctx.errors.unexpected_symbol(
ctx.nonterminal,
ctx.tokens.current(),
[terminals[x] for x in nonterminal_first[69] if x >=0],
rules[60]
)
# Lexer Code #
# START USER CODE
def init():
return {
'context': None,
'replacements': {
re.compile(r"\\n"): 0x000A,
re.compile(r"\\r"): 0x000D,
re.compile(r"\\b"): 0x0008,
re.compile(r"\\t"): 0x0009,
re.compile(r"\\a"): 0x0007,
re.compile(r"\\v"): 0x000B,
re.compile(r'\\"'): 0x0022,
re.compile(r"\\'"): 0x0027,
re.compile(r"\\\?"): 0x003F
},
'escapes': {
re.compile(r'(\\([0-7]{1,3}))'): 8,
re.compile(r'(\\[xX]([0-9a-fA-F]{1,4}))'): 16,
re.compile(r'(\\[uU]([0-9a-fA-F]{4}))'): 16
}
}
def workflow(ctx, terminal, source_string, line, col):
ctx.user_context['context'] = 'workflow'
default_action(ctx, terminal, source_string, line, col)
def task(ctx, terminal, source_string, line, col):
ctx.user_context['context'] = 'task'
default_action(ctx, terminal, source_string, line, col)
def output(ctx, terminal, source_string, line, col):
if ctx.user_context['context'] == 'workflow':
ctx.stack.append('wf_output')
default_action(ctx, terminal, source_string, line, col)
def wdl_unescape(ctx, terminal, source_string, line, col):
for regex, c in ctx.user_context['replacements'].items():
source_string = regex.sub(chr(c), source_string)
source_string = source_string.replace("\u005C\u005C", "\u005C")
for regex, base in ctx.user_context['escapes'].items():
for escape_sequence, number in regex.findall(source_string):
source_string = source_string.replace(escape_sequence, chr(int(number, base)))
default_action(ctx, terminal, source_string, line, col)
# END USER CODE
def emit(ctx, terminal, source_string, line, col):
if terminal:
ctx.tokens.append(Terminal(terminals[terminal], terminal, source_string, ctx.resource, line, col))
def default_action(ctx, terminal, source_string, line, col):
emit(ctx, terminal, source_string, line, col)
def post_filter(tokens):
return tokens
def destroy(context):
pass
class LexerStackPush:
def __init__(self, mode):
self.mode = mode
class LexerAction:
def __init__(self, action):
self.action = action
class LexerContext:
def __init__(self, string, resource, errors, user_context):
self.__dict__.update(locals())
self.stack = ['default']
self.line = 1
self.col = 1
self.tokens = []
self.user_context = user_context
self.re_match = None # https://docs.python.org/3/library/re.html#match-objects
class HermesLexer:
regex = {
'default': OrderedDict([
(re.compile(r'#.*'), [
# (terminal, group, function)
]),
(re.compile(r'\s+'), [
# (terminal, group, function)
]),
(re.compile(r'^version(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('version', 0, None),
LexerStackPush('awaiting_version_name'),
]),
]),
'main': OrderedDict([
(re.compile(r'\s+'), [
# (terminal, group, function)
]),
(re.compile(r'/\*(.*?)\*/', re.DOTALL), [
# (terminal, group, function)
]),
(re.compile(r'#.*'), [
# (terminal, group, function)
]),
(re.compile(r'task(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('task', 0, task),
]),
(re.compile(r'(call)\s+'), [
# (terminal, group, function)
('call', 1, None),
LexerStackPush('task_fqn'),
]),
(re.compile(r'workflow(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('workflow', 0, workflow),
]),
(re.compile(r'struct(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('struct', 0, None),
]),
(re.compile(r'import(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('import', 0, None),
]),
(re.compile(r'alias(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('alias', 0, None),
]),
(re.compile(r'input(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('input', 0, None),
]),
(re.compile(r'output(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('output', 0, None),
]),
(re.compile(r'as(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('as', 0, None),
]),
(re.compile(r'if(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('if', 0, None),
]),
(re.compile(r'then(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('then', 0, None),
]),
(re.compile(r'else(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('else', 0, None),
]),
(re.compile(r'runtime(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('runtime', 0, None),
]),
(re.compile(r'scatter(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('scatter', 0, None),
LexerStackPush('scatter'),
]),
(re.compile(r'command\s*(?=<<<)'), [
# (terminal, group, function)
('raw_command', 0, None),
LexerStackPush('raw_command2'),
]),
(re.compile(r'command\s*(?=\{)'), [
# (terminal, group, function)
('raw_command', 0, None),
LexerStackPush('raw_command'),
]),
(re.compile(r'parameter_meta(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('parameter_meta', 0, None),
]),
(re.compile(r'meta(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('meta', 0, None),
]),
(re.compile(r'(true|false)(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('boolean', 0, None),
]),
(re.compile(r'(object)\s*(\{)'), [
# (terminal, group, function)
('object', 0, None),
('lbrace', 0, None),
]),
(re.compile(r'(Array|Map|Object|Pair|Boolean|Int|Float|Uri|File|String)(?![a-zA-Z0-9_])(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('type', 0, None),
]),
(re.compile(r'[a-zA-Z]([a-zA-Z0-9_])*'), [
# (terminal, group, function)
('identifier', 0, None),
]),
(re.compile(r'null'), [
# (terminal, group, function)
('null', 0, None),
]),
(re.compile(r':'), [
# (terminal, group, function)
('colon', 0, None),
]),
(re.compile(r','), [
# (terminal, group, function)
('comma', 0, None),
]),
(re.compile(r'=='), [
# (terminal, group, function)
('double_equal', 0, None),
]),
(re.compile(r'\|\|'), [
# (terminal, group, function)
('double_pipe', 0, None),
]),
(re.compile(r'\&\&'), [
# (terminal, group, function)
('double_ampersand', 0, None),
]),
(re.compile(r'!='), [
# (terminal, group, function)
('not_equal', 0, None),
]),
(re.compile(r'='), [
# (terminal, group, function)
('equal', 0, None),
]),
(re.compile(r'\.'), [
# (terminal, group, function)
('dot', 0, None),
]),
(re.compile(r'\{'), [
# (terminal, group, function)
('lbrace', 0, None),
]),
(re.compile(r'\}'), [
# (terminal, group, function)
('rbrace', 0, None),
]),
(re.compile(r'\('), [
# (terminal, group, function)
('lparen', 0, None),
]),
(re.compile(r'\)'), [
# (terminal, group, function)
('rparen', 0, None),
]),
(re.compile(r'\['), [
# (terminal, group, function)
('lsquare', 0, None),
]),
(re.compile(r'\]'), [
# (terminal, group, function)
('rsquare', 0, None),
]),
(re.compile(r'\+'), [
# (terminal, group, function)
('plus', 0, None),
]),
(re.compile(r'\*'), [
# (terminal, group, function)
('asterisk', 0, None),
]),
(re.compile(r'-'), [
# (terminal, group, function)
('dash', 0, None),
]),
(re.compile(r'/'), [
# (terminal, group, function)
('slash', 0, None),
]),
(re.compile(r'%'), [
# (terminal, group, function)
('percent', 0, None),
]),
(re.compile(r'<='), [
# (terminal, group, function)
('lteq', 0, None),
]),
(re.compile(r'<'), [
# (terminal, group, function)
('lt', 0, None),
]),
(re.compile(r'>='), [
# (terminal, group, function)
('gteq', 0, None),
]),
(re.compile(r'>'), [
# (terminal, group, function)
('gt', 0, None),
]),
(re.compile(r'!'), [
# (terminal, group, function)
('not', 0, None),
]),
(re.compile(r'\"'), [
# (terminal, group, function)
('quote', 0, None),
LexerStackPush('dquote_string'),
]),
(re.compile(r'\''), [
# (terminal, group, function)
('quote', 0, None),
LexerStackPush('squote_string'),
]),
(re.compile(r'\?'), [
# (terminal, group, function)
('qmark', 0, None),
]),
(re.compile(r'-?[0-9]+\.[0-9]+'), [
# (terminal, group, function)
('float', 0, None),
]),
(re.compile(r'[0-9]+'), [
# (terminal, group, function)
('integer', 0, None),
]),
]),
'dquote_string': OrderedDict([
(re.compile(r'\"'), [
# (terminal, group, function)
('quote', 0, None),
LexerAction('pop'),
]),
(re.compile(r'\$\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'~\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'\\.'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
(re.compile(r'[^\\\"\$~]+'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
(re.compile(r'[~$](?!{)'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
(re.compile(r'[^\"\n(\$\{)(~\{)]*'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
]),
'squote_string': OrderedDict([
(re.compile(r'\''), [
# (terminal, group, function)
('quote', 0, None),
LexerAction('pop'),
]),
(re.compile(r'\$\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'~\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'\\.'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
(re.compile(r'[^\\\'\$~]+'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
(re.compile(r'[~$](?!{)'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
(re.compile(r'[^\'\n(\$\{)(~\{)]*'), [
# (terminal, group, function)
('string', 0, wdl_unescape),
]),
]),
'awaiting_version_name': OrderedDict([
(re.compile(r'\s+'), [
# (terminal, group, function)
]),
(re.compile(r'1.0'), [
# (terminal, group, function)
('version_name', 0, None),
LexerStackPush('main'),
]),
]),
'task_fqn': OrderedDict([
(re.compile(r'\s+'), [
# (terminal, group, function)
]),
(re.compile(r'[a-zA-Z]([a-zA-Z0-9_])*(\.[a-zA-Z]([a-zA-Z0-9_])*)*'), [
# (terminal, group, function)
('fqn', 0, None),
LexerAction('pop'),
]),
]),
'scatter': OrderedDict([
(re.compile(r'\s+'), [
# (terminal, group, function)
]),
(re.compile(r'\('), [
# (terminal, group, function)
('lparen', 0, None),
]),
(re.compile(r'in(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('in', 0, None),
LexerAction('pop'),
]),
(re.compile(r'[a-zA-Z]([a-zA-Z0-9_])*'), [
# (terminal, group, function)
('identifier', 0, None),
]),
]),
'raw_command': OrderedDict([
(re.compile(r'\{'), [
# (terminal, group, function)
('raw_cmd_start', 0, None),
]),
(re.compile(r'\}'), [
# (terminal, group, function)
('raw_cmd_end', 0, None),
LexerAction('pop'),
]),
(re.compile(r'\$\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'~\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'(.*?)(?=\$\{|~\{|\})', re.DOTALL), [
# (terminal, group, function)
('cmd_part', 0, None),
]),
]),
'raw_command2': OrderedDict([
(re.compile(r'<<<'), [
# (terminal, group, function)
('raw_cmd_start', 0, None),
]),
(re.compile(r'>>>'), [
# (terminal, group, function)
('raw_cmd_end', 0, None),
LexerAction('pop'),
]),
(re.compile(r'~\{'), [
# (terminal, group, function)
('expression_placeholder_start', 0, None),
LexerStackPush('expression_placeholder'),
]),
(re.compile(r'(.*?)(?=~\{|>>>)', re.DOTALL), [
# (terminal, group, function)
('cmd_part', 0, None),
]),
]),
'expression_placeholder': OrderedDict([
(re.compile(r'\s+'), [
# (terminal, group, function)
]),
(re.compile(r'\}'), [
# (terminal, group, function)
('expression_placeholder_end', 0, None),
LexerAction('pop'),
]),
(re.compile(r'\['), [
# (terminal, group, function)
('lsquare', 0, None),
]),
(re.compile(r'\]'), [
# (terminal, group, function)
('rsquare', 0, None),
]),
(re.compile(r'='), [
# (terminal, group, function)
('equal', 0, None),
]),
(re.compile(r'\+'), [
# (terminal, group, function)
('plus', 0, None),
]),
(re.compile(r'\*'), [
# (terminal, group, function)
('asterisk', 0, None),
]),
(re.compile(r'[0-9]+'), [
# (terminal, group, function)
('integer', 0, None),
]),
(re.compile(r'if'), [
# (terminal, group, function)
('if', 0, None),
]),
(re.compile(r'else'), [
# (terminal, group, function)
('else', 0, None),
]),
(re.compile(r'then'), [
# (terminal, group, function)
('then', 0, None),
]),
(re.compile(r'[a-zA-Z]([a-zA-Z0-9_])*(?=\s*=)'), [
# (terminal, group, function)
('cmd_attr_hint', None, None),
('identifier', 0, None),
]),
(re.compile(r'(true|false)(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('boolean', 0, None),
]),
(re.compile(r'(Array|Map|Object|Pair|Boolean|Int|Float|Uri|File|String)(?![a-zA-Z0-9_])(?![a-zA-Z0-9_])'), [
# (terminal, group, function)
('type', 0, None),
]),
(re.compile(r'[a-zA-Z]([a-zA-Z0-9_])*'), [
# (terminal, group, function)
('identifier', 0, None),
]),
(re.compile(r':'), [
# (terminal, group, function)
('colon', 0, None),
]),
(re.compile(r','), [
# (terminal, group, function)
('comma', 0, None),
]),
(re.compile(r'\.'), [
# (terminal, group, function)
('dot', 0, None),
]),
(re.compile(r'=='), [
# (terminal, group, function)
('double_equal', 0, None),
]),
(re.compile(r'\|\|'), [
# (terminal, group, function)
('double_pipe', 0, None),
]),
(re.compile(r'\&\&'), [
# (terminal, group, function)
('double_ampersand', 0, None),
]),
(re.compile(r'!='), [
# (terminal, group, function)
('not_equal', 0, None),
]),
(re.compile(r'='), [
# (terminal, group, function)
('equal', 0, None),
]),
(re.compile(r'\.'), [
# (terminal, group, function)
('dot', 0, None),
]),
(re.compile(r'\{'), [
# (terminal, group, function)
('lbrace', 0, None),
]),
(re.compile(r'\('), [
# (terminal, group, function)
('lparen', 0, None),
]),
(re.compile(r'\)'), [
# (terminal, group, function)
('rparen', 0, None),
]),
(re.compile(r'\['), [
# (terminal, group, function)
('lsquare', 0, None),
]),
(re.compile(r'\]'), [
# (terminal, group, function)
('rsquare', 0, None),
]),
(re.compile(r'\+'), [
# (terminal, group, function)
('plus', 0, None),
]),
(re.compile(r'\*'), [
# (terminal, group, function)
('asterisk', 0, None),
]),
(re.compile(r'-'), [
# (terminal, group, function)
('dash', 0, None),
]),
(re.compile(r'/'), [
# (terminal, group, function)
('slash', 0, None),
]),
(re.compile(r'%'), [
# (terminal, group, function)
('percent', 0, None),
]),
(re.compile(r'<='), [
# (terminal, group, function)
('lteq', 0, None),
]),
(re.compile(r'<'), [
# (terminal, group, function)
('lt', 0, None),
]),
(re.compile(r'>='), [
# (terminal, group, function)
('gteq', 0, None),
]),
(re.compile(r'>'), [
# (terminal, group, function)
('gt', 0, None),
]),
(re.compile(r'!'), [
# (terminal, group, function)
('not', 0, None),
]),
(re.compile(r'\"'), [
# (terminal, group, function)
('quote', 0, None),
LexerStackPush('dquote_string'),
]),
(re.compile(r'\''), [
# (terminal, group, function)
('quote', 0, None),
LexerStackPush('squote_string'),
]),
(re.compile(r'-?[0-9]+\.[0-9]+'), [
# (terminal, group, function)
('float', 0, None),
]),
(re.compile(r'[0-9]+'), [
# (terminal, group, function)
('integer', 0, None),
]),
]),
}
def _advance_line_col(self, string, length, line, col):
for i in range(length):
if string[i] == '\n':
line += 1
col = 1
else:
col += 1
return (line, col)
def _advance_string(self, ctx, string):
(ctx.line, ctx.col) = self._advance_line_col(string, len(string), ctx.line, ctx.col)
ctx.string = ctx.string[len(string):]
def _next(self, ctx, debug=False):
for regex, outputs in self.regex[ctx.stack[-1]].items():
if debug:
from xtermcolor import colorize
token_count = len(ctx.tokens)
print('{1} ({2}, {3}) regex: {0}'.format(
colorize(regex.pattern, ansi=40), colorize(ctx.string[:20].replace('\n', '\\n'), ansi=15), ctx.line, ctx.col)
)
match = regex.match(ctx.string)
if match:
ctx.re_match = match
for output in outputs:
if isinstance(output, tuple):
(terminal, group, function) = output
function = function if function else default_action
source_string = match.group(group) if group is not None else ''
(group_line, group_col) = self._advance_line_col(ctx.string, match.start(group) if group else 0, ctx.line, ctx.col)
function(
ctx,
terminal,
source_string,
group_line,
group_col
)
if debug:
print(' matched: {}'.format(colorize(match.group(0).replace('\n', '\\n'), ansi=3)))
for token in ctx.tokens[token_count:]:
print(' emit: [{}] [{}, {}] [{}] stack:{} context:{}'.format(
colorize(token.str, ansi=9),
colorize(str(token.line), ansi=5),
colorize(str(token.col), ansi=5),
colorize(token.source_string, ansi=3),
colorize(str(ctx.stack), ansi=4),
colorize(str(ctx.user_context), ansi=13)
))
token_count = len(ctx.tokens)
if isinstance(output, LexerStackPush):
ctx.stack.append(output.mode)
if debug:
print(' push on stack: {}'.format(colorize(output.mode, ansi=4)))
if isinstance(output, LexerAction):
if output.action == 'pop':
mode = ctx.stack.pop()
if debug:
print(' pop off stack: {}'.format(colorize(mode, ansi=4)))
self._advance_string(ctx, match.group(0))
return len(match.group(0)) > 0
return False
def lex(self, string, resource, errors=None, debug=False):
if errors is None:
errors = DefaultSyntaxErrorHandler()
string_copy = string
user_context = init()
ctx = LexerContext(string, resource, errors, user_context)
while len(ctx.string):
matched = self._next(ctx, debug)
if matched == False:
raise ctx.errors.unrecognized_token(string_copy, ctx.line, ctx.col)
destroy(ctx.user_context)
filtered = post_filter(ctx.tokens)
return filtered
def lex(source, resource, errors=None, debug=False):
return TokenStream(HermesLexer().lex(source, resource, errors, debug))
# Main #
def cli():
if len(sys.argv) != 3 or (sys.argv[1] not in ['parsetree', 'ast'] and sys.argv[1] != 'tokens'):
sys.stderr.write("Usage: {0} parsetree <source>\n".format(argv[0]))
sys.stderr.write("Usage: {0} ast <source>\n".format(argv[0]))
sys.stderr.write("Usage: {0} tokens <source>\n".format(argv[0]))
sys.exit(-1)
try:
with open(sys.argv[2]) as fp:
tokens = lex(fp.read(), os.path.basename(sys.argv[2]))
except SyntaxError as error:
sys.exit(error)
if sys.argv[1] in ['parsetree', 'ast']:
try:
tree = parse(tokens)
if sys.argv[1] == 'parsetree':
print(tree.dumps(indent=2))
else:
ast = tree.ast()
print(ast.dumps(indent=2) if ast else ast)
except SyntaxError as error:
print(error)
if sys.argv[1] == 'tokens':
for token in tokens:
print(token)
if __name__ == '__main__':
cli() | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/wdl_v1_parser.py | wdl_v1_parser.py |
import requests
from .types import CromwellBackendType, RestfulResponseType, WorkflowType, CromwellMetadataType
def restful_response(rsp: requests.Response):
if not rsp.ok:
raise RuntimeError(f"请求发生异常{rsp.reason}")
try:
data = rsp.json() # type: RestfulResponseType
except Exception as e:
raise RuntimeError(f"响应数据不是有效的json内容")
if data['code'] != 0:
raise RuntimeError(data['message'])
return data['data'], data['message']
def start_request(method: str, url: str, **options: dict):
try:
return requests.request(method=method, url=url, **options)
except Exception as e:
raise RuntimeError(f"请求发送异常{e}")
class WDLAPI(object):
API_PREFIXS = {
"backend": "/api/v1/backend/", # 管理backend
"workflow": "/api/v1/workflow/", # crowmell作业管理
"workflow_v2": "/api/v2/workflow/", # crowmell作业管理
}
def __init__(self, api: str, user: str) -> None:
self.api = api
self.owner = user
def submit(self, backend_name: str, jsonpath: str):
"""基于WDL模板提交分析任务"""
url = self.api + self.API_PREFIXS['workflow']
data = {
"owner": self.owner,
"backend_name": backend_name,
}
files = {"input": open(jsonpath, 'rb')}
rsp = requests.post(url, data=data, files=files)
_, message = restful_response(rsp)
return message
def submit_by_standrand_data(self, jsonpath: str):
"""基于标准数据格式提交分析任务"""
import json5
url = self.api + self.API_PREFIXS['workflow_v2']
# files = {"input": open(jsonpath, 'rb')}
data = json5.load(open(jsonpath, encoding='utf8'))
rsp = requests.post(url, json=data)
_, message = restful_response(rsp)
return message
def submit_action(self, action: str, data: dict, primary_value: str = 'action', expect_response_type: str="json"):
"""提交自定义操作:中止、重投
"""
# backend = self.config.get_cromwell_backend(backend_name)
# /{prefix}/{资源编号}/{操作名称} 或 /{prefix}/action/{操作名称}
url = self.api + self.API_PREFIXS['workflow'] + primary_value + "/" + action
item = {
"owner": self.owner,
# "backend_name": backend_name,
# "alias": backend_name,
**data
}
rsp = requests.post(url, data=item)
if expect_response_type != 'json':
return rsp
_, message = restful_response(rsp)
return message
def get_workflows(self, filters: dict = None, paginations: dict = None):
url = self.api + self.API_PREFIXS['workflow']
params = dict(filters)
if paginations:
params.update(paginations)
rsp = requests.get(url, params=params)
response: RestfulResponseType = rsp.json()
if response['code'] != 0:
raise RuntimeError(response['message'])
workflows: list[WorkflowType] = response['data']
return workflows, response['total']
def get_backends(self, alias: str = None):
url = self.api + self.API_PREFIXS['backend']
query = {"owner_$in": f"iknow,{self.owner}"}
if alias:
query['alias'] = alias
rsp = requests.get(url, params=query)
d = rsp.json() # type: RestfulResponseType
if d.get('code') != 0:
raise RuntimeError(d.get("message", "未知错误"))
backends = d.get('data') # type: list[CromwellBackendType]
if alias and backends:
backends = [backends]
return backends
def sync_backend(self, upload: bool = True):
"""同步本地和服务器上的backend配置
upload (bool): 指定上传 或 下载配置
"""
url = self.api + self.API_PREFIXS['backend']
if upload:
for alias, item in self.config.servers.items():
item['alias'] = alias
msg = f"{item['alias']}\t{item.get('backend', item['platform'])}\t{item['host']}\t"
try:
self.add_update_backend(item)
except Exception as e:
print(f"上传失败:{msg} {e}")
else:
print(f"上传成功: {msg}")
return
rsp = requests.get(url, params={"owner": self.owner})
rsp_data = rsp.json() # type: RestfulResponseType
if rsp_data['code'] != 0:
raise RuntimeError(f"查询服务器Cromwell Backend配置失败: {rsp_data['message']}")
backends = rsp_data['data'] # type: list[CromwellBackendType]
for backend in backends:
self.config.add_cromwell_backend(backend['backend'], {k: v for k,v in backend.items() if k not in ['_id', 'name', 'owner']})
print("下载配置成功")
self.config.pp(self.config.servers)
def add_update_backend(self, item: dict):
"""添加或更新backend
Args:
item (dict): 待添加或更新的backend
根据 平台 + alias 检查是否存在。若存在则更新,否则新增
若需要修改平台或alias,则需要先删除原backend在新增
"""
url = self.api + self.API_PREFIXS['backend']
data = dict(item)
data['owner'] = self.owner
if not data.get('backend') and data.get('platform'):
data['backend'] = data['platform']
del data['platform']
rsp = start_request('put', url, data=data)
_, msg = restful_response(rsp)
return msg
def delete_backend(self, alias: str):
# 1. 查询
url = self.api + self.API_PREFIXS['backend']
rsp = start_request('get', url, params={"owner": self.owner, "alias": alias})
data, _ = restful_response(rsp) # type: Tuple[List[CromwellBackendType], str]
if not data:
raise RuntimeError("未找到对应的Crowmell Backend配置")
cromwell = data[0]
rsp = start_request('delete', f"{url}/{cromwell['name']}")
print(restful_response(rsp)[1])
def validate_cromwell_id(self, cromwell_id: str, alias: str = None):
backend = self.config.get_cromwell_backend(alias)
# rsp = requests.post(f"{host}/api/workflows/v1", files=files)
try:
rsp = requests.get(f"{backend['host']}/api/workflows/v1/{cromwell_id}/status")
d = rsp.json()
# 成功时 d = {id, status}
# 失败时 d = {status, message}
if not d.get('id'):
raise RuntimeError(f"Cromwell校验失败:{d.get('message')}")
except Exception as e:
raise RuntimeError(f"Cromwell 编号校验失败: {e}")
return True
def get_metadata(self, primary_value: str) -> CromwellMetadataType:
api = self.api + self.API_PREFIXS['workflow']
url = f"{api}{primary_value}/metadata"
rsp = start_request('get', url)
metadata, _ = restful_response(rsp)
return metadata | yucebio-yc2-adaptor | /yucebio_yc2_adaptor-2.0.3-py3-none-any.whl/yucebio/yc2/adaptor/util/api.py | api.py |
# NestedNER
## Prerequisites
The main requirements are:
* tqdm
* flair
* word2vec
* glove-python-binary==0.2.0
* transformers==2.10.0
* wandb # for logging the results
* yaml
In the root directory, run
```bash
pip install -e .
```
## Data Format
```
{
"id": "train_2975",
"text": "ll Services Plan Documents Only ( Section 125 ) Premium Offset Plan ( POP ) Wellness Plans MBTA Corporate Transit Pass Program WMATA Smar Trip Transit / Parking Program Contact Us HRC Total Solutions 111 Charles Street Manchester , New hampshire 03101 customerservice @ hrcts . com Phone : ( 603 ) 647 - 1147 Fax : ( 866 ) 978 - 7868 Follow Us Linked In You Tube Twitter Resources IIAS Participating Pharmacies IIAS 90 % Merchant List FSA Store HSA St",
"entity_list": [
{"text": "111 Charles Street", "type": "detail", "char_span": [200, 218]},
{"text": "Manchester", "type": "city", "char_span": [219, 229]},
{"text": "New hampshire", "type": "state", "char_span": [232, 245]},
{"text": "03101", "type": "zipcode", "char_span": [246, 251]},
]
}
```
## Pretrained Model and Word Embeddings
Download [BERT-BASE-CASED](https://huggingface.co/bert-base-cased) and put it under `../pretrained_models`. Download [word embeddings](https://pan.baidu.com/s/1HcigyVBjsShTR2OAEzj5Og) (code: 8044) and put them under `../pretrained_emb`.
## Train
Set configuration in `tplinker_ner/train_config.yaml`. Start training:
```
cd tplinker_ner
python train.py
```
## Evaluation
Set configuration in `tplinker_ner/eval_config.yaml`. Start evaluation by running `tplinker_ner/Evaluation.ipynb`
| yucheng-ner | /yucheng_ner-0.6.tar.gz/yucheng_ner-0.6/README.md | README.md |
import re
from tqdm import tqdm
import torch
from IPython.core.debugger import set_trace
import copy
import torch
import torch.nn as nn
import json
from yucheng_ner.ner_common.components import HandshakingKernel
from torch.nn.parameter import Parameter
from transformers import AutoModel
from flair.data import Sentence
from flair.embeddings import FlairEmbeddings, StackedEmbeddings
import numpy as np
import pandas as pd
import word2vec
class HandshakingTaggingScheme:
def __init__(self, tags, max_seq_len, visual_field):
super().__init__()
self.visual_field = visual_field
self.tag2id = {t:idx for idx, t in enumerate(sorted(tags))}
self.id2tag = {idx:t for t, idx in self.tag2id.items()}
# mapping shaking sequence and matrix
self.matrix_size = max_seq_len
# e.g. [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
self.shaking_idx2matrix_idx = [(ind, end_ind) for ind in range(self.matrix_size) for end_ind in list(range(self.matrix_size))[ind:ind + visual_field]]
self.matrix_idx2shaking_idx = [[0 for i in range(self.matrix_size)] for j in range(self.matrix_size)]
for shaking_idx, matrix_idx in enumerate(self.shaking_idx2matrix_idx):
self.matrix_idx2shaking_idx[matrix_idx[0]][matrix_idx[1]] = shaking_idx
def get_spots(self, sample):
'''
spot: (start_pos, end_pos, tag_id)
'''
# term["tok_span"][1] - 1: span[1] is not included
spots = [(ent["tok_span"][0], ent["tok_span"][1] - 1, self.tag2id[ent["type"]]) for ent in sample["entity_list"]]
return spots
def spots2shaking_tag4batch(self, spots_batch):
'''
convert spots to shaking tag
spots_batch:
[spots1, spots2, ....]
spots: [(start_pos, end_pos, tag_id), ]
return: shaking tag
'''
shaking_seq_len = self.matrix_size * self.visual_field - self.visual_field * (self.visual_field - 1) // 2
shaking_seq_tag = torch.zeros([len(spots_batch), shaking_seq_len, len(self.tag2id)]).long()
for batch_idx, spots in enumerate(spots_batch):
for sp in spots:
shaking_ind = self.matrix_idx2shaking_idx[sp[0]][sp[1]]
shaking_seq_tag[batch_idx][shaking_ind][sp[2]] = 1
return shaking_seq_tag
def get_spots_fr_shaking_tag(self, shaking_tag):
'''
return matrix_spots: [(start_pos, end_pos, tag_id), ]
'''
matrix_spots = []
for point in torch.nonzero(shaking_tag, as_tuple = False): # shaking_tag.nonzero() -> torch.nonzero(shaking_tag, as_tuple = False)
shaking_idx, tag_idx = point[0].item(), point[1].item()
matrix_points = self.shaking_idx2matrix_idx[shaking_idx]
spot = (matrix_points[0], matrix_points[1], tag_idx)
matrix_spots.append(spot)
return matrix_spots
def decode_ent(self, text, shaking_tag, tok2char_span, tok_offset = 0, char_offset = 0):
'''
shaking_tag: size = (shaking_seq_len, tag_size)
if text is a subtext of test data, tok_offset and char_offset must be set
'''
matrix_spots = self.get_spots_fr_shaking_tag(shaking_tag)
entities = []
entity_memory_set = set()
for sp in matrix_spots:
char_spans = tok2char_span[sp[0]:sp[1] + 1]
char_sp = [char_spans[0][0], char_spans[-1][1]]
ent = text[char_sp[0]:char_sp[1]]
tag_id = sp[2]
ent_memory = "{}\u2E80{}\u2E80{}\u2E80{}".format(ent, *sp)
if ent_memory not in entity_memory_set:
entities.append({
"text": ent,
"tok_span": [sp[0] + tok_offset, sp[1] + 1 + tok_offset],
"char_span": [char_sp[0] + char_offset, char_sp[1] + char_offset],
"type": self.id2tag[tag_id],
})
entity_memory_set.add(ent_memory)
return entities
class DataMaker:
def __init__(self, handshaking_tagger,
word_tokenizer,
subword_tokenizer,
text2char_indices_func,
max_word_num,
max_subword_num,
max_char_num_in_tok
):
super().__init__()
self.handshaking_tagger = handshaking_tagger
self.word_tokenizer = word_tokenizer
self.subword_tokenizer = subword_tokenizer
self.text2char_indices_func = text2char_indices_func
self.max_word_num = max_word_num
self.max_subword_num = max_subword_num
self.max_char_num_in_tok = max_char_num_in_tok
def get_indexed_data(self, data, data_type = "train"):
'''
indexing data
if data_type == "test", matrix_spots is not included
'''
indexed_sample_list = []
max_word_num = self.max_word_num
max_subword_num = self.max_subword_num
max_char_num_in_tok = self.max_char_num_in_tok
max_word_num4flair = max([len(sample["text"].split(" ")) for sample in data]) # 这里主要考虑让flair脱离max_word_num的依赖,如果有bug,改回max_word_num。以后用到flair都要带上max_word_num。
for sample in tqdm(data, desc = "Generate indexed data"):
text = sample["text"]
indexed_sample = {}
indexed_sample["sample"] = sample
if self.subword_tokenizer is not None:
# codes for bert input
bert_codes = self.subword_tokenizer.encode_plus(text,
return_offsets_mapping = True,
add_special_tokens = False,
max_length = max_subword_num,
truncation = True,
pad_to_max_length = True)
# get bert codes
subword_input_ids = torch.tensor(bert_codes["input_ids"]).long()
attention_mask = torch.tensor(bert_codes["attention_mask"]).long()
token_type_ids = torch.tensor(bert_codes["token_type_ids"]).long()
subword2char_span = bert_codes["offset_mapping"]
indexed_sample["subword_input_ids"] = subword_input_ids
indexed_sample["attention_mask"] = attention_mask
indexed_sample["token_type_ids"] = token_type_ids
indexed_sample["tok2char_span"] = subword2char_span # token is subword level
# word level tokenizer
if self.word_tokenizer is not None: # use word enc
if self.subword_tokenizer is not None: # also use bert
indexed_sample["word_input_ids"] = self.word_tokenizer.text2word_indices(text, max_word_num)
# subword2word_idx_map: map subword to corresponding word
words = self.word_tokenizer.tokenize(text)
subword2word_idx_map = []
for wd_idx, wd in enumerate(words):
for subwd in self.subword_tokenizer.tokenize(wd):
if subwd != "[PAD]":
subword2word_idx_map.append(wd_idx)
if len(subword2word_idx_map) < max_subword_num:
subword2word_idx_map.extend([len(words) - 1] * (max_subword_num - len(subword2word_idx_map)))
subword2word_idx_map = torch.tensor(subword2word_idx_map).long()
indexed_sample["subword2word_idx_map"] = subword2word_idx_map
else: # do not use bert, but use word enc
word_codes = self.word_tokenizer.encode_plus(text, max_word_num)
word2char_span = word_codes["offset_mapping"]
indexed_sample["tok2char_span"] = word2char_span # token is word level
indexed_sample["word_input_ids"] = word_codes["input_ids"]
if self.text2char_indices_func is not None: # use char enc
char_input_ids = self.text2char_indices_func(text)
char_input_ids_padded = []
for span in indexed_sample["tok2char_span"]:
char_ids = char_input_ids[span[0]:span[1]]
if len(char_ids) < max_char_num_in_tok:
char_ids.extend([0] * (max_char_num_in_tok - len(char_ids)))
else:
char_ids = char_ids[:max_char_num_in_tok]
char_input_ids_padded.extend(char_ids)
char_input_ids_padded = torch.tensor(char_input_ids_padded).long()
indexed_sample["char_input_ids_padded"] = char_input_ids_padded
# prepare padded sentences for flair embeddings
words = text.split(" ")
words.extend(["[PAD]"] * (max_word_num4flair - len(words)))
indexed_sample["padded_sent"] = Sentence(" ".join(words))
# get spots
if data_type != "test":
matrix_spots = self.handshaking_tagger.get_spots(sample)
indexed_sample["matrix_spots"] = matrix_spots
indexed_sample_list.append(indexed_sample)
return indexed_sample_list
def generate_batch(self, batch_data, data_type = "train"):
batch_dict = {}
if self.subword_tokenizer is not None:
subword_input_ids_list = []
attention_mask_list = []
token_type_ids_list = []
for dt in batch_data:
subword_input_ids_list.append(dt["subword_input_ids"])
attention_mask_list.append(dt["attention_mask"])
token_type_ids_list.append(dt["token_type_ids"])
batch_dict["subword_input_ids"] = torch.stack(subword_input_ids_list, dim = 0)
batch_dict["attention_mask"] = torch.stack(attention_mask_list, dim = 0)
batch_dict["token_type_ids"] = torch.stack(token_type_ids_list, dim = 0)
if self.word_tokenizer is not None:
word_input_ids_list = [dt["word_input_ids"] for dt in batch_data]
batch_dict["word_input_ids"] = torch.stack(word_input_ids_list, dim = 0)
if self.subword_tokenizer is not None:
subword2word_idx_map_list = [dt["subword2word_idx_map"] for dt in batch_data]
batch_dict["subword2word_idx"] = torch.stack(subword2word_idx_map_list, dim = 0)
if self.text2char_indices_func is not None:
char_input_ids_padded_list = [dt["char_input_ids_padded"] for dt in batch_data]
batch_dict["char_input_ids"] = torch.stack(char_input_ids_padded_list, dim = 0)
# must
sample_list = []
tok2char_span_list = []
padded_sent_list = []
matrix_spots_batch = []
for dt in batch_data:
sample_list.append(dt["sample"])
tok2char_span_list.append(dt["tok2char_span"])
padded_sent_list.append(dt["padded_sent"])
if data_type != "test":
matrix_spots_batch.append(dt["matrix_spots"])
batch_dict["sample_list"] = sample_list
batch_dict["tok2char_span_list"] = tok2char_span_list
batch_dict["padded_sents"] = padded_sent_list
# shaking tag
if data_type != "test":
batch_dict["shaking_tag"] = self.handshaking_tagger.spots2shaking_tag4batch(matrix_spots_batch)
return batch_dict
class TPLinkerNER(nn.Module):
def __init__(self,
char_encoder_config,
word_encoder_config,
flair_config,
handshaking_kernel_config,
hidden_size,
activate_enc_fc,
entity_type_num,
bert_config):
super().__init__()
'''
char_encoder_config = {
"char_size": len(char2idx), #
"emb_dim": char_emb_dim,
"emb_dropout": char_emb_dropout,
"bilstm_layers": char_bilstm_layers,
"bilstm_dropout": char_bilstm_dropout,
"max_char_num_in_tok": max_char_num_in_tok,
}
bert_config = {
"path": encoder_path,
"fintune": bert_finetune,
"use_last_k_layers": use_last_k_layers_hiddens,
}
word_encoder_config = {
"init_word_embedding_matrix": init_word_embedding_matrix,
"emb_dropout": word_emb_dropout,
"bilstm_layers": word_bilstm_layers,
"bilstm_dropout": word_bilstm_dropout,
"freeze_word_emb": freeze_word_emb,
}
handshaking_kernel_config = {
"shaking_type": hyper_parameters["shaking_type"],
"context_type": hyper_parameters["context_type"],
"visual_field": visual_field, #
}
'''
combined_hidden_size = 0
self.char_encoder_config = char_encoder_config
if char_encoder_config is not None:
# char encoder
char_size = char_encoder_config["char_size"]
char_emb_dim = char_encoder_config["emb_dim"]
char_emb_dropout = char_encoder_config["emb_dropout"]
char_bilstm_hidden_size = char_encoder_config["bilstm_hidden_size"]
char_bilstm_layers = char_encoder_config["bilstm_layers"]
char_bilstm_dropout = char_encoder_config["bilstm_dropout"]
max_char_num_in_subword = char_encoder_config["max_char_num_in_tok"]
self.char_emb = nn.Embedding(char_size, char_emb_dim)
self.char_emb_dropout = nn.Dropout(p = char_emb_dropout)
self.char_lstm_l1 = nn.LSTM(char_emb_dim,
char_bilstm_hidden_size[0] // 2,
num_layers = char_bilstm_layers[0],
dropout = char_bilstm_dropout[0],
bidirectional = True,
batch_first = True)
self.char_lstm_dropout = nn.Dropout(p = char_bilstm_dropout[1])
self.char_lstm_l2 = nn.LSTM(char_bilstm_hidden_size[0],
char_bilstm_hidden_size[1] // 2,
num_layers = char_bilstm_layers[1],
dropout = char_bilstm_dropout[2],
bidirectional = True,
batch_first = True)
self.char_cnn = nn.Conv1d(char_bilstm_hidden_size[1], char_bilstm_hidden_size[1], max_char_num_in_subword, stride = max_char_num_in_subword)
combined_hidden_size += char_bilstm_hidden_size[1]
# word encoder
## init word embedding
self.word_encoder_config = word_encoder_config
if word_encoder_config is not None:
word2idx = word_encoder_config["word2idx"]
word_size = len(word2idx)
word_emb_key = word_encoder_config["emb_key"]
word_emb_dropout = word_encoder_config["emb_dropout"]
word_bilstm_hidden_size = word_encoder_config["bilstm_hidden_size"]
word_bilstm_layers = word_encoder_config["bilstm_layers"]
word_bilstm_dropout = word_encoder_config["bilstm_dropout"]
freeze_word_emb = word_encoder_config["freeze_word_emb"]
print("Loading pretrained word embeddings...")
if word_emb_key == "glove":
glove_df = pd.read_csv('../../pretrained_emb/glove/glove.6B.100d.txt', sep=" ", quoting = 3, header = None, index_col = 0)
pretrained_emb = {key: val.values for key, val in glove_df.T.items()}
word_emb_dim = len(list(pretrained_emb.values())[0])
elif word_emb_key == "pubmed":
pretrained_emb = word2vec.load('../../pretrained_emb/bio_nlp_vec/PubMed-shuffle-win-30.bin')
word_emb_dim = len(pretrained_emb.vectors[0])
init_word_embedding_matrix = np.random.normal(-0.5, 0.5, size=(word_size, word_emb_dim))
hit_count = 0
for word, idx in tqdm(word2idx.items(), desc = "Init word embedding matrix"):
if word in pretrained_emb:
hit_count += 1
init_word_embedding_matrix[idx] = pretrained_emb[word]
print("pretrained word embedding hit rate: {}".format(hit_count / word_size))
init_word_embedding_matrix = torch.FloatTensor(init_word_embedding_matrix)
## word encoder model
self.word_emb = nn.Embedding.from_pretrained(init_word_embedding_matrix, freeze = freeze_word_emb)
self.word_emb_dropout = nn.Dropout(p = word_emb_dropout)
self.word_lstm_l1 = nn.LSTM(word_emb_dim,
word_bilstm_hidden_size[0] // 2,
num_layers = word_bilstm_layers[0],
dropout = word_bilstm_dropout[0],
bidirectional = True,
batch_first = True)
self.word_lstm_dropout = nn.Dropout(p = word_bilstm_dropout[1])
self.word_lstm_l2 = nn.LSTM(word_bilstm_hidden_size[0],
word_bilstm_hidden_size[1] // 2,
num_layers = word_bilstm_layers[1],
dropout = word_bilstm_dropout[2],
bidirectional = True,
batch_first = True)
combined_hidden_size += word_bilstm_hidden_size[1]
# bert
self.bert_config = bert_config
if bert_config is not None:
bert_path = bert_config["path"]
bert_finetune = bert_config["finetune"]
self.use_last_k_layers_bert = bert_config["use_last_k_layers"]
self.bert = AutoModel.from_pretrained(bert_path)
if not bert_finetune: # if train without finetuning bert
for param in self.bert.parameters():
param.requires_grad = False
# hidden_size = self.bert.config.hidden_size
combined_hidden_size += self.bert.config.hidden_size
# flair
self.flair_config = flair_config
if flair_config is not None:
embedding_models = [FlairEmbeddings(emb_id) for emb_id in flair_config["embedding_ids"]]
self.stacked_flair_embeddings_model = StackedEmbeddings(embedding_models)
combined_hidden_size += embedding_models[0].embedding_length * len(embedding_models)
# encoding fc
self.enc_fc = nn.Linear(combined_hidden_size, hidden_size)
self.activate_enc_fc = activate_enc_fc
# handshaking kernel
shaking_type = handshaking_kernel_config["shaking_type"]
context_type = handshaking_kernel_config["context_type"]
visual_field = handshaking_kernel_config["visual_field"]
self.handshaking_kernel = HandshakingKernel(hidden_size, shaking_type, context_type, visual_field)
# decoding fc
self.dec_fc = nn.Linear(hidden_size, entity_type_num)
def forward(self, char_input_ids = None,
word_input_ids = None,
padded_sents = None,
subword_input_ids = None,
attention_mask = None,
token_type_ids = None,
subword2word_idx = None):
# features
features = []
# char
if self.char_encoder_config is not None:
# char_input_ids: (batch_size, seq_len * max_char_num_in_subword)
# char_input_emb/char_hiddens: (batch_size, seq_len * max_char_num_in_subword, char_emb_dim)
# char_conv_oudtut: (batch_size, seq_len, char_emb_dim)
char_input_emb = self.char_emb(char_input_ids)
char_input_emb = self.char_emb_dropout(char_input_emb)
char_hiddens, _ = self.char_lstm_l1(char_input_emb)
char_hiddens, _ = self.char_lstm_l2(self.char_lstm_dropout(char_hiddens))
char_conv_oudtut = self.char_cnn(char_hiddens.permute(0, 2, 1)).permute(0, 2, 1)
features.append(char_conv_oudtut)
# word
if self.word_encoder_config is not None:
# word_input_ids: (batch_size, seq_len)
# word_input_emb/word_hiddens: batch_size, seq_len, word_emb_dim)
word_input_emb = self.word_emb(word_input_ids)
word_input_emb = self.word_emb_dropout(word_input_emb)
word_hiddens, _ = self.word_lstm_l1(word_input_emb)
word_hiddens, _ = self.word_lstm_l2(self.word_lstm_dropout(word_hiddens))
if self.bert_config is not None:
# chose and repeat word hiddens, to align with subword num
word_hiddens = torch.gather(word_hiddens, 1, subword2word_idx[:,:,None].repeat(1, 1, word_hiddens.size()[-1]))
features.append(word_hiddens)
# flair embeddings
if self.flair_config is not None:
self.stacked_flair_embeddings_model.embed(padded_sents)
flair_embeddings = torch.stack([torch.stack([tok.embedding for tok in sent]) for sent in padded_sents])
if self.bert_config is not None:
# chose and repeat word hiddens, to align with subword num
flair_embeddings = torch.gather(flair_embeddings, 1, subword2word_idx[:,:,None].repeat(1, 1, flair_embeddings.size()[-1]))
features.append(flair_embeddings)
if self.bert_config is not None:
# subword_input_ids, attention_mask, token_type_ids: (batch_size, seq_len)
context_oudtuts = self.bert(subword_input_ids, attention_mask, token_type_ids)
# last_hidden_state: (batch_size, seq_len, hidden_size)
hidden_states = context_oudtuts[2]
subword_hiddens = torch.mean(torch.stack(list(hidden_states)[-self.use_last_k_layers_bert:], dim = 0), dim = 0)
features.append(subword_hiddens)
# combine features
combined_hiddens = self.enc_fc(torch.cat(features, dim = -1))
if self.activate_enc_fc:
combined_hiddens = torch.tanh(combined_hiddens)
# shaking_hiddens: (batch_size, shaking_seq_len, hidden_size)
# shaking_seq_len: max_seq_len * vf - sum(1, vf)
shaking_hiddens = self.handshaking_kernel(combined_hiddens)
# ent_shaking_oudtuts: (batch_size, shaking_seq_len, entity_type_num)
ent_shaking_oudtuts = self.dec_fc(shaking_hiddens)
return ent_shaking_oudtuts
class Metrics:
def __init__(self, handshaking_tagger):
super().__init__()
self.handshaking_tagger = handshaking_tagger
self.last_weights = None
def GHM(self, gradient, bins = 10, beta = 0.9):
'''
gradient_norm: gradient_norms of all examples in this batch; (batch_size, shaking_seq_len)
'''
avg = torch.mean(gradient)
std = torch.std(gradient) + 1e-12
gradient_norm = torch.sigmoid((gradient - avg) / std) # normalization and pass through sigmoid to 0 ~ 1.
min_, max_ = torch.min(gradient_norm), torch.max(gradient_norm)
gradient_norm = (gradient_norm - min_) / (max_ - min_)
gradient_norm = torch.clamp(gradient_norm, 0, 0.9999999) # ensure elements in gradient_norm != 1.
example_sum = torch.flatten(gradient_norm).size()[0] # N
# calculate weights
current_weights = torch.zeros(bins).to(gradient.device)
hits_vec = torch.zeros(bins).to(gradient.device)
count_hits = 0 # coungradient_normof hits
for i in range(bins):
bar = float((i + 1) / bins)
hits = torch.sum((gradient_norm <= bar)) - count_hits
count_hits += hits
hits_vec[i] = hits.item()
current_weights[i] = example_sum / bins / (hits.item() + example_sum / bins )
# EMA: exponential moving averaging
# print()
# print("hits_vec: {}".format(hits_vec))
# print("current_weights: {}".format(current_weights))
if self.last_weights is None:
self.last_weights = torch.ones(bins).to(gradient.device) # init by ones
current_weights = self.last_weights * beta + (1 - beta) * current_weights
self.last_weights = current_weights
# print("ema current_weights: {}".format(current_weights))
# weights4examples: pick weights for all examples
weight_pk_idx = (gradient_norm / (1 / bins)).long()[:, :, None]
weights_rp = current_weights[None, None, :].repeat(gradient_norm.size()[0], gradient_norm.size()[1], 1)
weights4examples = torch.gather(weights_rp, -1, weight_pk_idx).squeeze(-1)
weights4examples /= torch.sum(weights4examples)
return weights4examples * gradient # return weighted gradients
# loss func
def _multilabel_categorical_crossentropy(self, y_pred, y_true):
"""
y_pred: (batch_size, shaking_seq_len, type_size)
y_true: (batch_size, shaking_seq_len, type_size)
y_true and y_pred have the same shape,elements in y_true are either 0 or 1,
1 tags positive classes,0 tags negtive classes(means tok-pair does not have this type of link).
"""
y_pred = y_pred.float()
y_true = y_true.float()
y_pred = (1 - 2 * y_true) * y_pred # -1 -> pos classes, 1 -> neg classes
y_pred_neg = y_pred - y_true * 1e12 # mask the pred oudtuts of pos classes
y_pred_pos = y_pred - (1 - y_true) * 1e12 # mask the pred oudtuts of neg classes
zeros = torch.zeros_like(y_pred[..., :1]) # st - st
y_pred_neg = torch.cat([y_pred_neg, zeros], dim = -1)
y_pred_pos = torch.cat([y_pred_pos, zeros], dim = -1)
neg_loss = torch.logsumexp(y_pred_neg, dim = -1)
pos_loss = torch.logsumexp(y_pred_pos, dim = -1)
return (self.GHM(neg_loss + pos_loss, bins = 1000)).sum()
def loss_func(self, y_pred, y_true):
return self._multilabel_categorical_crossentropy(y_pred, y_true)
def get_sample_accuracy(self, pred, truth):
'''
tag全等正确率
'''
# # (batch_size, ..., seq_len, tag_size) -> (batch_size, ..., seq_len)
# pred_id = torch.argmax(pred, dim = -1).int()
# (batch_size, ..., seq_len) -> (batch_size, -1)
pred = pred.view(pred.size()[0], -1)
truth = truth.view(truth.size()[0], -1)
# (batch_size, ),每个元素是pred与truth之间tag相同的数量
correct_tag_num = torch.sum(torch.eq(truth, pred).float(), dim = 1)
# seq维上所有tag必须正确,所以correct_tag_num必须等于seq的长度才算一个correct的sample
sample_acc_ = torch.eq(correct_tag_num, torch.ones_like(correct_tag_num) * truth.size()[-1]).float()
sample_acc = torch.mean(sample_acc_, axis=0)
return sample_acc
def get_ent_correct_pred_glod_num(self,gold_sample_list,
offset_map_list,
batch_pred_ent_shaking_seq_tag):
correct_num, pred_num, gold_num = 0, 0, 0
for ind in range(len(gold_sample_list)):
gold_sample = gold_sample_list[ind]
text = gold_sample["text"]
offset_map = offset_map_list[ind]
pred_ent_shaking_seq_tag = batch_pred_ent_shaking_seq_tag[ind]
pred_entities = self.handshaking_tagger.decode_ent(text, pred_ent_shaking_seq_tag, offset_map)
gold_entities = gold_sample["entity_list"]
pred_num += len(pred_entities)
gold_num += len(gold_entities)
memory_set = set()
for ent in gold_entities:
memory_set.add("{}\u2E80{}\u2E80{}".format(ent["tok_span"][0], ent["tok_span"][1], ent["type"]))
for ent in pred_entities:
hit = "{}\u2E80{}\u2E80{}".format(ent["tok_span"][0], ent["tok_span"][1], ent["type"])
if hit in memory_set:
correct_num += 1
return correct_num, pred_num, gold_num
def get_scores(self, correct_num, pred_num, gold_num):
minimini = 1e-10
precision = correct_num / (pred_num + minimini)
recall = correct_num / (gold_num + minimini)
f1 = 2 * precision * recall / (precision + recall + minimini)
return precision, recall, f1 | yucheng-ner | /yucheng_ner-0.6.tar.gz/yucheng_ner-0.6/yucheng_ner/tplinker_ner/tplinker_ner.py | tplinker_ner.py |
from IPython.core.debugger import set_trace
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import time
class CLNGRU(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.reset_cln = LayerNorm(hidden_size, hidden_size, conditional = True)
self.update_cln = LayerNorm(hidden_size, hidden_size, conditional = True)
self.input_cln = LayerNorm(hidden_size, hidden_size, conditional = True)
def forward(self, sequence):
# sequence: (batch_size, sequence_len, hidden_size)
hidden = torch.zeros_like(sequence[:, 0, :])
hiddens = []
for i in range(sequence.size()[1]):
current_input = sequence[:, i, :]
reset_gate = torch.sigmoid(self.reset_cln(current_input, hidden))
update_gate = torch.sigmoid(self.update_cln(current_input, hidden))
hidden_candidate = torch.tanh(self.input_cln(current_input, reset_gate * hidden))
hidden = hidden_candidate * update_gate + (1 - update_gate) * hidden
hiddens.append(hidden)
return torch.stack(hiddens, dim = 1), hidden
class CLNRNN(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.cln = LayerNorm(hidden_size, hidden_size, conditional = True)
def forward(self, sequence):
# sequence: (batch_size, sequence_len, hidden_size)
hidden = torch.zeros_like(sequence[:, 0, :])
hiddens = []
for i in range(sequence.size()[1]):
current_input = sequence[:, i, :]
hidden = self.cln(current_input, hidden)
hiddens.append(hidden)
return torch.stack(hiddens, dim = 1), hidden
class HandshakingKernel(nn.Module):
def __init__(self, hidden_size, shaking_type, context_type, visual_field):
super().__init__()
self.shaking_type = shaking_type
self.visual_field = visual_field
self.context_type = context_type
if shaking_type == "cln":
self.cond_layer_norm = LayerNorm(hidden_size, hidden_size, conditional = True)
elif shaking_type == "cln_plus":
self.tok_pair_cln = LayerNorm(hidden_size, hidden_size, conditional = True)
self.context_cln = LayerNorm(hidden_size, hidden_size, conditional = True)
elif shaking_type == "cln_plus2":
self.combine_fc = nn.Linear(hidden_size * 2, hidden_size)
self.cln = LayerNorm(hidden_size, hidden_size, conditional = True)
elif shaking_type == "cln_plus3":
self.cln_start_tok = LayerNorm(hidden_size, hidden_size, conditional = True)
self.cln_end_tok = LayerNorm(hidden_size, hidden_size, conditional = True)
elif shaking_type == "cat":
self.combine_fc = nn.Linear(hidden_size * 2, hidden_size)
elif shaking_type == "cat_plus":
self.combine_fc = nn.Linear(hidden_size * 3, hidden_size)
elif shaking_type == "res_gate":
self.Wg = nn.Linear(hidden_size, hidden_size)
self.Wo = nn.Linear(hidden_size * 3, hidden_size)
if context_type == "mix_pooling":
self.lamtha = Parameter(torch.rand(hidden_size))
elif context_type == "lstm":
self.context_lstm = nn.LSTM(hidden_size,
hidden_size,
num_layers = 1,
bidirectional = False,
batch_first = True)
elif context_type == "clngru":
self.clngru = CLNGRU(hidden_size)
elif context_type == "clnrnn":
self.clnrnn = CLNRNN(hidden_size)
def get_context_hiddens(self, seq_hiddens, context_type = "mean_pooling"):
# seq_hiddens: (batch_size, seq_len, hidden_size)
def pool(seqence, pooling_type):
if pooling_type == "mean_pooling":
pooling = torch.mean(seqence, dim = -2)
elif pooling_type == "max_pooling":
pooling, _ = torch.max(seqence, dim = -2)
elif pooling_type == "mix_pooling":
pooling = self.lamtha * torch.mean(seqence, dim = -2) + (1 - self.lamtha) * torch.max(seqence, dim = -2)[0]
return pooling
if "pooling" in context_type:
context = torch.stack([pool(seq_hiddens[:, :i+1, :], context_type) for i in range(seq_hiddens.size()[1])], dim = 1)
elif context_type == "lstm":
context, _ = self.context_lstm(seq_hiddens)
elif context_type == "clngru":
context, _ = self.clngru(seq_hiddens)
elif context_type == "clnrnn":
context, _ = self.clnrnn(seq_hiddens)
return context
def forward(self, seq_hiddens):
'''
seq_hiddens: (batch_size, seq_len, hidden_size)
return:
shaking_hiddenss:
shaking_seq_len: seq_len * visual_field - visual_field * (visual_field - 1) / 2
cln: (batch_size, shaking_seq_len, hidden_size) (32, 5 * 3 - (2 + 1), 768)
cat: (batch_size, shaking_seq_len, hidden_size * 2)
'''
seq_len = seq_hiddens.size()[-2]
shaking_hiddens_list = []
padding_context = torch.zeros_like(seq_hiddens[:, 0,:])
for start_idx in range(seq_len):
hidden_each_step = seq_hiddens[:, start_idx, :]
# seq_len - start_idx: only shake afterwards
repeat_len = min(seq_len - start_idx, self.visual_field)
repeat_current_hiddens = hidden_each_step[:, None, :].repeat(1, repeat_len, 1)
visual_hiddens = seq_hiddens[:, start_idx:start_idx + self.visual_field, :]
# context bt tok pairs
context = self.get_context_hiddens(visual_hiddens, self.context_type)
# context_list = []
# for i in range(visual_hiddens.size()[1]):
# end_idx = start_idx + i
# ent_context = self.pooling(seq_hiddens[:, start_idx:end_idx + 1, :], self.context_type)
# bf_context = self.pooling(seq_hiddens[:, :start_idx, :], self.context_type) if start_idx != 0 else padding_context
# af_context = self.pooling(seq_hiddens[:, end_idx + 1:, :], self.context_type) if end_idx + 1 != seq_hiddens.size()[-2] else padding_context
# context_list.append((ent_context + bf_context + af_context) / 3)
# context = torch.stack(context_list, dim = 1)
# set_trace()
if self.shaking_type == "cln":
shaking_hiddens = self.cond_layer_norm(visual_hiddens, repeat_current_hiddens)
elif self.shaking_type == "pooling":
shaking_hiddens = context
elif self.shaking_type == "cln_plus2":
tok_pair_hiddens = torch.cat([repeat_current_hiddens, visual_hiddens], dim = -1)
tok_pair_hiddens = torch.tanh(self.combine_fc(tok_pair_hiddens))
shaking_hiddens = self.cln(context, tok_pair_hiddens)
elif self.shaking_type == "cln_plus":
shaking_hiddens = self.tok_pair_cln(visual_hiddens, repeat_current_hiddens)
shaking_hiddens = self.context_cln(shaking_hiddens, context)
elif self.shaking_type == "cln_plus3":
shaking_hiddens = self.cln_start_tok(context, repeat_current_hiddens)
shaking_hiddens = self.cln_end_tok(shaking_hiddens, visual_hiddens)
elif self.shaking_type == "cat":
shaking_hiddens = torch.cat([repeat_current_hiddens, visual_hiddens], dim = -1)
shaking_hiddens = torch.tanh(self.combine_fc(shaking_hiddens))
elif self.shaking_type == "cat_plus":
shaking_hiddens = torch.cat([repeat_current_hiddens, visual_hiddens, context], dim = -1)
shaking_hiddens = torch.tanh(self.combine_fc(shaking_hiddens))
elif self.shaking_type == "res_gate":
gate = torch.sigmoid(self.Wg(repeat_current_hiddens))
cond_hiddens = visual_hiddens * gate
res_hiddens = torch.cat([repeat_current_hiddens, visual_hiddens, cond_hiddens], dim = -1)
shaking_hiddens = torch.tanh(self.Wo(res_hiddens))
else:
raise ValueError("Wrong shaking_type!")
shaking_hiddens_list.append(shaking_hiddens)
long_shaking_hiddens = torch.cat(shaking_hiddens_list, dim = 1)
return long_shaking_hiddens
class LayerNorm(nn.Module):
def __init__(self, input_dim, cond_dim = 0, center = True, scale = True, epsilon = None, conditional = False,
hidden_units = None, hidden_activation = 'linear', hidden_initializer = 'xaiver', **kwargs):
super(LayerNorm, self).__init__()
"""
input_dim: inputs.shape[-1]
cond_dim: cond.shape[-1]
"""
self.center = center
self.scale = scale
self.conditional = conditional
self.hidden_units = hidden_units
# self.hidden_activation = activations.get(hidden_activation) keras中activation为linear时,返回原tensor,unchanged
self.hidden_initializer = hidden_initializer
self.epsilon = epsilon or 1e-12
self.input_dim = input_dim
self.cond_dim = cond_dim
if self.center:
self.beta = Parameter(torch.zeros(input_dim))
if self.scale:
self.gamma = Parameter(torch.ones(input_dim))
if self.conditional:
if self.hidden_units is not None:
self.hidden_dense = nn.Linear(in_features = self.cond_dim, out_features = self.hidden_units, bias=False)
if self.center:
self.beta_dense = nn.Linear(in_features = self.cond_dim, out_features = input_dim, bias=False)
if self.scale:
self.gamma_dense = nn.Linear(in_features = self.cond_dim, out_features = input_dim, bias=False)
self.initialize_weights()
def initialize_weights(self):
if self.conditional:
if self.hidden_units is not None:
if self.hidden_initializer == 'normal':
torch.nn.init.normal(self.hidden_dense.weight)
elif self.hidden_initializer == 'xavier': # glorot_uniform
torch.nn.init.xavier_uniform_(self.hidden_dense.weight)
# 下面这两个为什么都初始化为0呢?
# 为了防止扰乱原来的预训练权重,两个变换矩阵可以全零初始化(单层神经网络可以用全零初始化,连续的多层神经网络才不应当用全零初始化),这样在初始状态,模型依然保持跟原来的预训练模型一致。
if self.center:
torch.nn.init.constant_(self.beta_dense.weight, 0)
if self.scale:
torch.nn.init.constant_(self.gamma_dense.weight, 0)
def forward(self, inputs, cond=None):
"""
如果是条件Layer Norm,则cond不是None
"""
if self.conditional:
if self.hidden_units is not None:
cond = self.hidden_dense(cond)
# for _ in range(K.ndim(inputs) - K.ndim(cond)): # K.ndim: 以整数形式返回张量中的轴数。
# TODO: 这两个为什么有轴数差呢? 为什么在 dim=1 上增加维度??
# 为了保持维度一致,cond可以是(batch_size, cond_dim)
for _ in range(len(inputs.shape) - len(cond.shape)):
cond = cond.unsqueeze(1) # cond = K.expand_dims(cond, 1)
# cond在加入beta和gamma之前做一次线性变换,以保证与input维度一致
if self.center:
beta = self.beta_dense(cond) + self.beta
if self.scale:
gamma = self.gamma_dense(cond) + self.gamma
else:
if self.center:
beta = self.beta
if self.scale:
gamma = self.gamma
outputs = inputs
if self.center:
mean = torch.mean(outputs, dim=-1).unsqueeze(-1)
outputs = outputs - mean
if self.scale:
variance = torch.mean(outputs**2, dim=-1).unsqueeze(-1)
std = (variance + self.epsilon) **2
outputs = outputs / std
outputs = outputs * gamma
if self.center:
outputs = outputs + beta
return outputs | yucheng-ner | /yucheng_ner-0.6.tar.gz/yucheng_ner-0.6/yucheng_ner/ner_common/components.py | components.py |
import re
from tqdm import tqdm
from IPython.core.debugger import set_trace
import copy
from transformers import BertTokenizerFast
import torch
class WordTokenizer:
def __init__(self, word2idx = None):
self.word2idx = word2idx
def tokenize(self, text):
return text.split(" ")
def text2word_indices(self, text, max_length = -1):
if not self.word2idx:
raise ValueError("if you invoke text2word_indices, self.word2idx should be set when initialize WordTokenizer")
word_ids = []
words = text.split(" ")
for w in words:
if w not in self.word2idx:
word_ids.append(self.word2idx['<UNK>'])
else:
word_ids.append(self.word2idx[w])
if len(word_ids) < max_length:
word_ids.extend([self.word2idx['<PAD>']] * (max_length - len(word_ids)))
if max_length != -1:
word_ids = torch.tensor(word_ids[:max_length]).long()
return word_ids
def get_word2char_span_map(self, text, max_length = -1):
words = self.tokenize(text)
word2char_span = []
char_num = 0
for wd in words:
word2char_span.append([char_num, char_num + len(wd)])
char_num += len(wd) + 1 # +1: whitespace
if len(word2char_span) < max_length:
word2char_span.extend([[0, 0]] * (max_length - len(word2char_span)))
if max_length != -1:
word2char_span = word2char_span[:max_length]
return word2char_span
def encode_plus(self, text, max_length = -1):
return {
"input_ids": self.text2word_indices(text, max_length),
"offset_mapping": self.get_word2char_span_map(text, max_length)
}
class Preprocessor:
def __init__(self, tokenizer, for_bert):
'''
if token_type == "subword", tokenizer must be set to bert encoder
"word", word tokenizer
'''
self.for_bert = for_bert
if for_bert:
self.tokenize = tokenizer.tokenize
self.get_tok2char_span_map = lambda text: tokenizer.encode_plus(text,
return_offsets_mapping = True,
add_special_tokens = False)["offset_mapping"]
else:
self.tokenize = tokenizer.tokenize
self.get_tok2char_span_map = lambda text: tokenizer.get_word2char_span_map(text)
def clean_data_wo_span(self, ori_data, separate = False, data_type = "train"):
'''
rm duplicate whitespaces
and separate special characters from tokens
'''
def clean_text(text):
text = re.sub("\s+", " ", text).strip()
if separate:
text = re.sub("([^A-Za-z0-9])", r" \1 ", text)
text = re.sub("\s+", " ", text).strip()
return text
for sample in tqdm(ori_data, desc = "clean data wo span"):
sample["text"] = clean_text(sample["text"])
if data_type == "test":
continue
for ent in sample["entity_list"]:
ent["text"] = clean_text(ent["text"])
return ori_data
def clean_data_w_span(self, ori_data):
'''
add a stake to bad samples and remove them from the clean data
'''
def strip_white(entity, entity_char_span):
p = 0
while entity[p] == " ":
entity_char_span[0] += 1
p += 1
p = len(entity) - 1
while entity[p] == " ":
entity_char_span[1] -= 1
p -= 1
return entity.strip(), entity_char_span
bad_samples, clean_data = [], []
for sample in tqdm(ori_data, desc = "clean data w span"):
text = sample["text"]
bad = False
for ent in sample["entity_list"]:
# rm whitespaces
ent["text"], ent["char_span"] = strip_white(ent["text"], ent["char_span"])
char_span = ent["char_span"]
if ent["text"] not in text or ent["text"] != text[char_span[0]:char_span[1]]:
ent["stake"] = 0
bad = True
if bad:
bad_samples.append(copy.deepcopy(sample))
new_ent_list = [ent for ent in sample["entity_list"] if "stake" not in ent]
if len(new_ent_list) > 0:
sample["entity_list"] = new_ent_list
clean_data.append(sample)
return clean_data, bad_samples
def _get_char2tok_span(self, text):
'''
map character level span to token level span
'''
tok2char_span = self.get_tok2char_span_map(text)
# get the number of characters
char_num = None
for tok_ind in range(len(tok2char_span) - 1, -1, -1):
if tok2char_span[tok_ind][1] != 0:
char_num = tok2char_span[tok_ind][1]
break
# build a map: char index to token level span
char2tok_span = [[-1, -1] for _ in range(char_num)] # 除了空格,其他字符均有对应token
for tok_ind, char_sp in enumerate(tok2char_span):
for char_ind in range(char_sp[0], char_sp[1]):
tok_sp = char2tok_span[char_ind]
# 因为char to tok 也可能出现1对多的情况,比如韩文。所以char_span的pos1以第一个tok_ind为准,pos2以最后一个tok_ind为准
if tok_sp[0] == -1:
tok_sp[0] = tok_ind
tok_sp[1] = tok_ind + 1
return char2tok_span
def _get_ent2char_spans(self, text, entities, ignore_subword = True):
'''
map entity to all possible character spans
e.g. {"entity1": [[0, 1], [18, 19]]}
if ignore_subword, look for entities with whitespace around, e.g. "entity" -> " entity "
'''
entities = sorted(entities, key = lambda x: len(x), reverse = True)
text_cp = " {} ".format(text) if ignore_subword else text
ent2char_spans = {}
for ent in entities:
spans = []
target_ent = " {} ".format(ent) if ignore_subword else ent
for m in re.finditer(re.escape(target_ent), text_cp):
span = [m.span()[0], m.span()[1] - 2] if ignore_subword else m.span()
spans.append(span)
# if len(spans) == 0:
# set_trace()
ent2char_spans[ent] = spans
return ent2char_spans
def add_char_span(self, dataset, ignore_subword = True):
samples_w_wrong_entity = [] # samples with entities that do not exist in the text, please check if any
for sample in tqdm(dataset, desc = "Adding char level spans"):
entities = [ent["text"] for ent in sample["entity_list"]]
ent2char_spans = self._get_ent2char_spans(sample["text"], entities, ignore_subword = ignore_subword)
# filter
ent_memory_set = set()
uni_entity_list = []
for ent in sample["entity_list"]:
ent_memory = "{}-{}".format(ent["text"], ent["type"])
if ent_memory not in ent_memory_set:
uni_entity_list.append(ent)
ent_memory_set.add(ent_memory)
new_ent_list = []
for ent in uni_entity_list:
ent_spans = ent2char_spans[ent["text"]]
for sp in ent_spans:
new_ent_list.append({
"text": ent["text"],
"type": ent["type"],
"char_span": sp,
})
if len(sample["entity_list"]) > len(new_ent_list):
samples_w_wrong_entity.append(sample)
sample["entity_list"] = new_ent_list
return dataset, samples_w_wrong_entity
def add_tok_span(self, data):
'''
data: char span is required
'''
for sample in tqdm(data, desc = "Adding token level span"):
text = sample["text"]
char2tok_span = self._get_char2tok_span(sample["text"])
for ent in sample["entity_list"]:
char_span = ent["char_span"]
tok_span_list = char2tok_span[char_span[0]:char_span[1]]
tok_span = [tok_span_list[0][0], tok_span_list[-1][1]]
ent["tok_span"] = tok_span
return data
def check_tok_span(self, data):
entities_to_fix = []
for sample in tqdm(data, desc = "check tok spans"):
text = sample["text"]
tok2char_span = self.get_tok2char_span_map(text)
for ent in sample["entity_list"]:
tok_span = ent["tok_span"]
char_span_list = tok2char_span[tok_span[0]:tok_span[1]]
char_span = [char_span_list[0][0], char_span_list[-1][1]]
text_extr = text[char_span[0]:char_span[1]]
gold_char_span = ent["char_span"]
if not(char_span[0] == gold_char_span[0] and char_span[1] == gold_char_span[1] and text_extr == ent["text"]):
bad_ent = copy.deepcopy(ent)
bad_ent["extr_text"] = text_extr
entities_to_fix.append(bad_ent)
span_error_memory = set()
for ent in entities_to_fix:
err_mem = "gold: {} --- extr: {}".format(ent["text"], ent["extr_text"])
span_error_memory.add(err_mem)
return span_error_memory
def split_into_short_samples(self,
sample_list,
max_seq_len,
sliding_len = 50,
data_type = "train"):
new_sample_list = []
for sample in tqdm(sample_list, desc = "Splitting"):
medline_id = sample["id"]
text = sample["text"]
tokens = self.tokenize(text)
tok2char_span = self.get_tok2char_span_map(text)
# sliding on token level
for start_ind in range(0, len(tokens), sliding_len):
if self.for_bert: # if use bert, do not split a word into two samples
while "##" in tokens[start_ind]:
start_ind -= 1
end_ind = start_ind + max_seq_len
tok_spans = tok2char_span[start_ind:end_ind]
char_span = (tok_spans[0][0], tok_spans[-1][-1])
sub_text = text[char_span[0]:char_span[1]]
if data_type == "test":
if len(sub_text) > 0:
new_sample = {
"id": medline_id,
"text": sub_text,
"tok_offset": start_ind,
"char_offset": char_span[0],
}
new_sample_list.append(new_sample)
else:
sub_entity_list = []
for term in sample["entity_list"]:
tok_span = term["tok_span"]
if tok_span[0] >= start_ind and tok_span[1] <= end_ind:
new_term = copy.deepcopy(term)
new_term["tok_span"] = [tok_span[0] - start_ind, tok_span[1] - start_ind]
new_term["char_span"][0] -= char_span[0]
new_term["char_span"][1] -= char_span[0]
sub_entity_list.append(new_term)
# if len(sub_entity_list) > 0:
new_sample = {
"id": medline_id,
"text": sub_text,
"entity_list": sub_entity_list,
}
new_sample_list.append(new_sample)
if end_ind > len(tokens):
break
return new_sample_list | yucheng-ner | /yucheng_ner-0.6.tar.gz/yucheng_ner-0.6/yucheng_ner/ner_common/utils.py | utils.py |
# `YuDown`
Download Youtube Media from this script and have a wonderful output😋
## Installation
To install and run the script:
```console
python3 -m venv venv
pip install yudown
yudown --help
```
## Run Locally
To launch the project, you need [Poetry](https://python-poetry.org) to be installed
Clone the project
```console
git clone https://github.com/TianaNanta/yudown.git
```
Go to the project directory
```console
cd yudown
```
Install dependencies
```console
poetry install
```
Launch the project
```console
poetry run python -m yudown --help
```
## Usage
**Usage**:
```console
yudown [OPTIONS] COMMAND [ARGS]...
```
**Options**:
* `-v, --version`: Show the application's version and exit.
* `--install-completion`: Install completion for the current shell.
* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.
* `--help`: Show this message and exit.
**Commands**:
* `download`: Download file from [red]Youtube[/red] 📥
* `history`: Show the download [blue]history[/blue] ⌚️
* `playlist`: Download Youtube [yellow]Playlist[/yellow]...
* `search`: [blue]Search[/blue] for video on Youtube 🔍
## `yudown download`
Download file from [red]Youtube[/red] 📥
**Usage**:
```console
yudown download [OPTIONS] [LINKS]...
```
**Arguments**:
* `[LINKS]...`
**Options**:
* `-t, --type TEXT`: The type of media to download [default: video]
* `-l, --location PATH`: Location of the downloaded file [default: ~/YuDown/notSpecified]
* `--help`: Show this message and exit.
## `yudown history`
Show the download [blue]history[/blue] ⌚️
**Usage**:
```console
yudown history [OPTIONS]
```
**Options**:
* `-D, --delete`
* `--help`: Show this message and exit.
## `yudown playlist`
Download Youtube [yellow]Playlist[/yellow] video 📼
**Usage**:
```console
yudown playlist [OPTIONS] [LINK]
```
**Arguments**:
* `[LINK]`
**Options**:
* `-l, --location PATH`: Location of the files to download [default: /home/nanta/YuDown/Playlist]
* `--help`: Show this message and exit.
## `yudown search`
[blue]Search[/blue] for video on Youtube 🔍
**Usage**:
```console
yudown search [OPTIONS] [SEARCH_QUERY]
```
**Arguments**:
* `[SEARCH_QUERY]`: The word you are searching for
**Options**:
* `-s, --suggestion`: Show search suggestion
* `--help`: Show this message and exit.
## Authors
* [@TianaNanta](https://www.github.com/TianaNanta)
## License
[MIT](https://choosealicense.com/licenses/mit/)
| yudown | /yudown-0.6.0.tar.gz/yudown-0.6.0/README.md | README.md |
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):b(a.RSVP=a.RSVP||{})}(this,function(a){"use strict";function b(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function c(a){var b=a._promiseCallbacks;return b||(b=a._promiseCallbacks={}),b}function d(a,b){if(2!==arguments.length)return wa[a];wa[a]=b}function e(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function f(a){return"function"==typeof a}function g(a){return null!==a&&"object"==typeof a}function h(a){return null!==a&&"object"==typeof a}function i(){setTimeout(function(){for(var a=0;a<Aa.length;a++){var b=Aa[a],c=b.payload;c.guid=c.key+c.id,c.childGuid=c.key+c.childId,c.error&&(c.stack=c.error.stack),wa.trigger(b.name,b.payload)}Aa.length=0},50)}function j(a,b,c){1===Aa.push({name:a,payload:{key:b._guidKey,id:b._id,eventName:a,detail:b._result,childId:c&&c._id,label:b._label,timeStamp:za(),error:wa["instrument-with-stack"]?new Error(b._label):null}})&&i()}function k(a,b){var c=this;if(a&&"object"==typeof a&&a.constructor===c)return a;var d=new c(m,b);return s(d,a),d}function l(){return new TypeError("A promises callback cannot return that same promise.")}function m(){}function n(a){try{return a.then}catch(a){return Ea.error=a,Ea}}function o(a,b,c,d){try{a.call(b,c,d)}catch(a){return a}}function p(a,b,c){wa.async(function(a){var d=!1,e=o(c,b,function(c){d||(d=!0,b!==c?s(a,c,void 0):u(a,c))},function(b){d||(d=!0,v(a,b))},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,v(a,e))},a)}function q(a,b){b._state===Ca?u(a,b._result):b._state===Da?(b._onError=null,v(a,b._result)):w(b,void 0,function(c){b!==c?s(a,c,void 0):u(a,c)},function(b){return v(a,b)})}function r(a,b,c){b.constructor===a.constructor&&c===C&&a.constructor.resolve===k?q(a,b):c===Ea?(v(a,Ea.error),Ea.error=null):f(c)?p(a,b,c):u(a,b)}function s(a,b){a===b?u(a,b):e(b)?r(a,b,n(b)):u(a,b)}function t(a){a._onError&&a._onError(a._result),x(a)}function u(a,b){a._state===Ba&&(a._result=b,a._state=Ca,0===a._subscribers.length?wa.instrument&&j("fulfilled",a):wa.async(x,a))}function v(a,b){a._state===Ba&&(a._state=Da,a._result=b,wa.async(t,a))}function w(a,b,c,d){var e=a._subscribers,f=e.length;a._onError=null,e[f]=b,e[f+Ca]=c,e[f+Da]=d,0===f&&a._state&&wa.async(x,a)}function x(a){var b=a._subscribers,c=a._state;if(wa.instrument&&j(c===Ca?"fulfilled":"rejected",a),0!==b.length){for(var d=void 0,e=void 0,f=a._result,g=0;g<b.length;g+=3)d=b[g],e=b[g+c],d?A(c,d,e,f):e(f);a._subscribers.length=0}}function y(){this.error=null}function z(a,b){try{return a(b)}catch(a){return Fa.error=a,Fa}}function A(a,b,c,d){var e=f(c),g=void 0,h=void 0;if(e){if((g=z(c,d))===Fa)h=g.error,g.error=null;else if(g===b)return void v(b,l())}else g=d;b._state!==Ba||(e&&void 0===h?s(b,g):void 0!==h?v(b,h):a===Ca?u(b,g):a===Da&&v(b,g))}function B(a,b){var c=!1;try{b(function(b){c||(c=!0,s(a,b))},function(b){c||(c=!0,v(a,b))})}catch(b){v(a,b)}}function C(a,b,c){var d=this,e=d._state;if(e===Ca&&!a||e===Da&&!b)return wa.instrument&&j("chained",d,d),d;d._onError=null;var f=new d.constructor(m,c),g=d._result;if(wa.instrument&&j("chained",d,f),e===Ba)w(d,f,a,b);else{var h=e===Ca?a:b;wa.async(function(){return A(e,f,h,g)})}return f}function D(a,b,c){return a===Ca?{state:"fulfilled",value:c}:{state:"rejected",reason:c}}function E(a,b){return ya(a)?new Ga(this,a,!0,b).promise:this.reject(new TypeError("Promise.all must be called with an array"),b)}function F(a,b){var c=this,d=new c(m,b);if(!ya(a))return v(d,new TypeError("Promise.race must be called with an array")),d;for(var e=0;d._state===Ba&&e<a.length;e++)w(c.resolve(a[e]),void 0,function(a){return s(d,a)},function(a){return v(d,a)});return d}function G(a,b){var c=this,d=new c(m,b);return v(d,a),d}function H(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function I(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function J(){this.value=void 0}function K(a){try{return a.then}catch(a){return Ka.value=a,Ka}}function L(a,b,c){try{a.apply(b,c)}catch(a){return Ka.value=a,Ka}}function M(a,b){for(var c={},d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=a[f];for(var g=0;g<b.length;g++){c[b[g]]=e[g+1]}return c}function N(a){for(var b=a.length,c=new Array(b-1),d=1;d<b;d++)c[d-1]=a[d];return c}function O(a,b){return{then:function(c,d){return a.call(b,c,d)}}}function P(a,b){var c=function(){for(var c=this,d=arguments.length,e=new Array(d+1),f=!1,g=0;g<d;++g){var h=arguments[g];if(!f){if((f=S(h))===La){var i=new Ja(m);return v(i,La.value),i}f&&!0!==f&&(h=O(f,h))}e[g]=h}var j=new Ja(m);return e[d]=function(a,c){a?v(j,a):void 0===b?s(j,c):!0===b?s(j,N(arguments)):ya(b)?s(j,M(arguments,b)):s(j,c)},f?R(j,e,a,c):Q(j,e,a,c)};return c.__proto__=a,c}function Q(a,b,c,d){var e=L(c,d,b);return e===Ka&&v(a,e.value),a}function R(a,b,c,d){return Ja.all(b).then(function(b){var e=L(c,d,b);return e===Ka&&v(a,e.value),a})}function S(a){return!(!a||"object"!=typeof a)&&(a.constructor===Ja||K(a))}function T(a,b){return Ja.all(a,b)}function U(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function V(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function W(a,b){return ya(a)?new Ma(Ja,a,b).promise:Ja.reject(new TypeError("Promise.allSettled must be called with an array"),b)}function X(a,b){return Ja.race(a,b)}function Y(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function Z(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function $(a,b){return g(a)?new Oa(Ja,a,b).promise:Ja.reject(new TypeError("Promise.hash must be called with an object"),b)}function _(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function aa(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function ba(a,b){return g(a)?new Pa(Ja,a,!1,b).promise:Ja.reject(new TypeError("RSVP.hashSettled must be called with an object"),b)}function ca(a){throw setTimeout(function(){throw a}),a}function da(a){var b={resolve:void 0,reject:void 0};return b.promise=new Ja(function(a,c){b.resolve=a,b.reject=c},a),b}function ea(a,b,c){return ya(a)?f(b)?Ja.all(a,c).then(function(a){for(var d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=b(a[f]);return Ja.all(e,c)}):Ja.reject(new TypeError("RSVP.map expects a function as a second argument"),c):Ja.reject(new TypeError("RSVP.map must be called with an array"),c)}function fa(a,b){return Ja.resolve(a,b)}function ga(a,b){return Ja.reject(a,b)}function ha(a,b){return Ja.all(a,b)}function ia(a,b){return Ja.resolve(a,b).then(function(a){return ha(a,b)})}function ja(a,b,c){return ya(a)||g(a)&&void 0!==a.then?f(b)?(ya(a)?ha(a,c):ia(a,c)).then(function(a){for(var d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=b(a[f]);return ha(e,c).then(function(b){for(var c=new Array(d),e=0,f=0;f<d;f++)b[f]&&(c[e]=a[f],e++);return c.length=e,c})}):Ja.reject(new TypeError("RSVP.filter expects function as a second argument"),c):Ja.reject(new TypeError("RSVP.filter must be called with an array or promise"),c)}function ka(a,b){Xa[Qa]=a,Xa[Qa+1]=b,2===(Qa+=2)&&Ya()}function la(){var a=process.nextTick,b=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);return Array.isArray(b)&&"0"===b[1]&&"10"===b[2]&&(a=setImmediate),function(){return a(qa)}}function ma(){return void 0!==Ra?function(){Ra(qa)}:pa()}function na(){var a=0,b=new Ua(qa),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){return c.data=a=++a%2}}function oa(){var a=new MessageChannel;return a.port1.onmessage=qa,function(){return a.port2.postMessage(0)}}function pa(){return function(){return setTimeout(qa,1)}}function qa(){for(var a=0;a<Qa;a+=2){(0,Xa[a])(Xa[a+1]),Xa[a]=void 0,Xa[a+1]=void 0}Qa=0}function ra(){try{var a=require,b=a("vertx");return Ra=b.runOnLoop||b.runOnContext,ma()}catch(a){return pa()}}function sa(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function ta(){wa.on.apply(wa,arguments)}function ua(){wa.off.apply(wa,arguments)}var va={mixin:function(a){return a.on=this.on,a.off=this.off,a.trigger=this.trigger,a._promiseCallbacks=void 0,a},on:function(a,d){if("function"!=typeof d)throw new TypeError("Callback must be a function");var e=c(this),f=void 0;f=e[a],f||(f=e[a]=[]),-1===b(f,d)&&f.push(d)},off:function(a,d){var e=c(this),f=void 0,g=void 0;if(!d)return void(e[a]=[]);f=e[a],-1!==(g=b(f,d))&&f.splice(g,1)},trigger:function(a,b,d){var e=c(this),f=void 0;if(f=e[a])for(var g=0;g<f.length;g++)(0,f[g])(b,d)}},wa={instrument:!1};va.mixin(wa);var xa=void 0;xa=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)};var ya=xa,za=Date.now||function(){return(new Date).getTime()},Aa=[],Ba=void 0,Ca=1,Da=2,Ea=new y,Fa=new y,Ga=function(){function a(a,b,c,d){this._instanceConstructor=a,this.promise=new a(m,d),this._abortOnReject=c,this._init.apply(this,arguments)}return a.prototype._init=function(a,b){var c=b.length||0;this.length=c,this._remaining=c,this._result=new Array(c),this._enumerate(b),0===this._remaining&&u(this.promise,this._result)},a.prototype._enumerate=function(a){for(var b=this.length,c=this.promise,d=0;c._state===Ba&&d<b;d++)this._eachEntry(a[d],d)},a.prototype._settleMaybeThenable=function(a,b){var c=this._instanceConstructor,d=c.resolve;if(d===k){var e=n(a);if(e===C&&a._state!==Ba)a._onError=null,this._settledAt(a._state,b,a._result);else if("function"!=typeof e)this._remaining--,this._result[b]=this._makeResult(Ca,b,a);else if(c===Ja){var f=new c(m);r(f,a,e),this._willSettleAt(f,b)}else this._willSettleAt(new c(function(b){return b(a)}),b)}else this._willSettleAt(d(a),b)},a.prototype._eachEntry=function(a,b){h(a)?this._settleMaybeThenable(a,b):(this._remaining--,this._result[b]=this._makeResult(Ca,b,a))},a.prototype._settledAt=function(a,b,c){var d=this.promise;d._state===Ba&&(this._abortOnReject&&a===Da?v(d,c):(this._remaining--,this._result[b]=this._makeResult(a,b,c),0===this._remaining&&u(d,this._result)))},a.prototype._makeResult=function(a,b,c){return c},a.prototype._willSettleAt=function(a,b){var c=this;w(a,void 0,function(a){return c._settledAt(Ca,b,a)},function(a){return c._settledAt(Da,b,a)})},a}(),Ha="rsvp_"+za()+"-",Ia=0,Ja=function(){function a(b,c){this._id=Ia++,this._label=c,this._state=void 0,this._result=void 0,this._subscribers=[],wa.instrument&&j("created",this),m!==b&&("function"!=typeof b&&H(),this instanceof a?B(this,b):I())}return a.prototype._onError=function(a){var b=this;wa.after(function(){b._onError&&wa.trigger("error",a,b._label)})},a.prototype.catch=function(a,b){return this.then(void 0,a,b)},a.prototype.finally=function(a,b){var c=this,d=c.constructor;return c.then(function(b){return d.resolve(a()).then(function(){return b})},function(b){return d.resolve(a()).then(function(){throw b})},b)},a}();Ja.cast=k,Ja.all=E,Ja.race=F,Ja.resolve=k,Ja.reject=G,Ja.prototype._guidKey=Ha,Ja.prototype.then=C;var Ka=new J,La=new J,Ma=function(a){function b(b,c,d){return U(this,a.call(this,b,c,!1,d))}return V(b,a),b}(Ga);Ma.prototype._makeResult=D;var Na=Object.prototype.hasOwnProperty,Oa=function(a){function b(b,c){var d=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],e=arguments[3];return Y(this,a.call(this,b,c,d,e))}return Z(b,a),b.prototype._init=function(a,b){this._result={},this._enumerate(b),0===this._remaining&&u(this.promise,this._result)},b.prototype._enumerate=function(a){var b=this.promise,c=[];for(var d in a)Na.call(a,d)&&c.push({position:d,entry:a[d]});var e=c.length;this._remaining=e;for(var f=void 0,g=0;b._state===Ba&&g<e;g++)f=c[g],this._eachEntry(f.entry,f.position)},b}(Ga),Pa=function(a){function b(b,c,d){return _(this,a.call(this,b,c,!1,d))}return aa(b,a),b}(Oa);Pa.prototype._makeResult=D;var Qa=0,Ra=void 0,Sa="undefined"!=typeof window?window:void 0,Ta=Sa||{},Ua=Ta.MutationObserver||Ta.WebKitMutationObserver,Va="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Wa="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,Xa=new Array(1e3),Ya=void 0;Ya=Va?la():Ua?na():Wa?oa():void 0===Sa&&"function"==typeof require?ra():pa();if("object"==typeof self)self;else{if("object"!=typeof global)throw new Error("no global: `self` or `global` found");global}var Za;wa.async=ka,wa.after=function(a){return setTimeout(a,0)};var $a=fa,_a=function(a,b){return wa.async(a,b)};if("undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var ab=window.__PROMISE_INSTRUMENTATION__;d("instrument",!0);for(var bb in ab)ab.hasOwnProperty(bb)&&ta(bb,ab[bb])}var cb=(Za={asap:ka,cast:$a,Promise:Ja,EventTarget:va,all:T,allSettled:W,race:X,hash:$,hashSettled:ba,rethrow:ca,defer:da,denodeify:P,configure:d,on:ta,off:ua,resolve:fa,reject:ga,map:ea},sa(Za,"async",_a),sa(Za,"filter",ja),Za);a.default=cb,a.asap=ka,a.cast=$a,a.Promise=Ja,a.EventTarget=va,a.all=T,a.allSettled=W,a.race=X,a.hash=$,a.hashSettled=ba,a.rethrow=ca,a.defer=da,a.denodeify=P,a.configure=d,a.on=ta,a.off=ua,a.resolve=fa,a.reject=ga,a.map=ea,a.async=_a,a.filter=ja,Object.defineProperty(a,"__esModule",{value:!0})});var EPUBJS=EPUBJS||{};EPUBJS.core={};var ELEMENT_NODE=1,TEXT_NODE=3,COMMENT_NODE=8,DOCUMENT_NODE=9;EPUBJS.core.getEl=function(a){return document.getElementById(a)},EPUBJS.core.getEls=function(a){return document.getElementsByClassName(a)},EPUBJS.core.request=function(a,b,c){var d,e=window.URL,f=e?"blob":"arraybuffer",g=new RSVP.defer,h=new XMLHttpRequest,i=XMLHttpRequest.prototype,j=function(){var a;this.readyState==this.DONE&&(200!==this.status&&0!==this.status||!this.response?g.reject({message:this.response,stack:(new Error).stack}):(a="xml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xml"):"xhtml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xhtml+xml"):"html"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"text/html"):"json"==b?JSON.parse(this.response):"blob"==b?e?this.response:new Blob([this.response]):this.response,g.resolve(a)))};return"overrideMimeType"in i||Object.defineProperty(i,"overrideMimeType",{value:function(a){}}),h.onreadystatechange=j,h.open("GET",a,!0),c&&(h.withCredentials=!0),b||(d=EPUBJS.core.uri(a),b=d.extension,b={htm:"html"}[b]||b),"blob"==b&&(h.responseType=f),"json"==b&&h.setRequestHeader("Accept","application/json"),"xml"==b&&(h.responseType="document",h.overrideMimeType("text/xml")),"xhtml"==b&&(h.responseType="document"),"html"==b&&(h.responseType="document"),"binary"==b&&(h.responseType="arraybuffer"),h.send(),g.promise},EPUBJS.core.toArray=function(a){var b=[];for(var c in a){var d;a.hasOwnProperty(c)&&(d=a[c],d.ident=c,b.push(d))}return b},EPUBJS.core.uri=function(a){var b,c,d,e={protocol:"",host:"",path:"",origin:"",directory:"",base:"",filename:"",extension:"",fragment:"",href:a},f=a.indexOf("blob:"),g=a.indexOf("://"),h=a.indexOf("?"),i=a.indexOf("#");return 0===f?(e.protocol="blob",e.base=a.indexOf(0,i),e):(-1!=i&&(e.fragment=a.slice(i+1),a=a.slice(0,i)),-1!=h&&(e.search=a.slice(h+1),a=a.slice(0,h),href=e.href),-1!=g?(e.protocol=a.slice(0,g),b=a.slice(g+3),d=b.indexOf("/"),-1===d?(e.host=e.path,e.path=""):(e.host=b.slice(0,d),e.path=b.slice(d)),e.origin=e.protocol+"://"+e.host,e.directory=EPUBJS.core.folder(e.path),e.base=e.origin+e.directory):(e.path=a,e.directory=EPUBJS.core.folder(a),e.base=e.directory),e.filename=a.replace(e.base,""),c=e.filename.lastIndexOf("."),-1!=c&&(e.extension=e.filename.slice(c+1)),e)},EPUBJS.core.folder=function(a){var b=a.lastIndexOf("/");if(-1==b);return a.slice(0,b+1)},EPUBJS.core.dataURLToBlob=function(a){var b,c,d,e,f,g=";base64,";if(-1==a.indexOf(g))return b=a.split(","),c=b[0].split(":")[1],d=b[1],new Blob([d],{type:c});b=a.split(g),c=b[0].split(":")[1],d=window.atob(b[1]),e=d.length,f=new Uint8Array(e);for(var h=0;h<e;++h)f[h]=d.charCodeAt(h);return new Blob([f],{type:c})},EPUBJS.core.addScript=function(a,b,c){var d,e;e=!1,d=document.createElement("script"),d.type="text/javascript",d.async=!1,d.src=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.addScripts=function(a,b,c){var d=a.length,e=0,f=function(){e++,d==e?b&&b():EPUBJS.core.addScript(a[e],f,c)};EPUBJS.core.addScript(a[e],f,c)},EPUBJS.core.addCss=function(a,b,c){var d,e;e=!1,d=document.createElement("link"),d.type="text/css",d.rel="stylesheet",d.href=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.prefixed=function(a){var b=["Webkit","Moz","O","ms"],c=a[0].toUpperCase()+a.slice(1),d=b.length;if(void 0!==document.documentElement.style[a])return a;for(var e=0;e<d;e++)if(void 0!==document.documentElement.style[b[e]+c])return b[e]+c;return a},EPUBJS.core.resolveUrl=function(a,b){var c,d,e=[],f=EPUBJS.core.uri(b),g=a.split("/");return f.host?b:(g.pop(),d=b.split("/"),d.forEach(function(a){".."===a?g.pop():e.push(a)}),c=g.concat(e),c.join("/"))},EPUBJS.core.uuid=function(){var a=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(b){var c=(a+16*Math.random())%16|0;return a=Math.floor(a/16),("x"==b?c:7&c|8).toString(16)})},EPUBJS.core.insert=function(a,b,c){var d=EPUBJS.core.locationOf(a,b,c);return b.splice(d,0,a),d},EPUBJS.core.locationOf=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:a<b?-1:(a=b)?0:void 0}),h-g<=0?i:(f=c(b[i],a),h-g==1?f>0?i:i+1:0===f?i:-1===f?EPUBJS.core.locationOf(a,b,c,i,h):EPUBJS.core.locationOf(a,b,c,g,i))},EPUBJS.core.indexOfSorted=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:a<b?-1:(a=b)?0:void 0}),h-g<=0?-1:(f=c(b[i],a),h-g==1?0===f?i:-1:0===f?i:-1===f?EPUBJS.core.indexOfSorted(a,b,c,i,h):EPUBJS.core.indexOfSorted(a,b,c,g,i))},EPUBJS.core.queue=function(a){var b=[],c=a,d=function(a,c,d){return b.push({funcName:a,args:c,context:d}),b},e=function(){var a;b.length&&(a=b.shift(),c[a.funcName].apply(a.context||c,a.args))};return{enqueue:d,dequeue:e,flush:function(){for(;b.length;)e()},clear:function(){b=[]},length:function(){return b.length}}},EPUBJS.core.getElementXPath=function(a){return a&&a.id?'//*[@id="'+a.id+'"]':EPUBJS.core.getElementTreeXPath(a)},EPUBJS.core.getElementTreeXPath=function(a){var b,c,d,e,f=[],g="http://www.w3.org/1999/xhtml"===a.ownerDocument.documentElement.getAttribute("xmlns");for(a.nodeType===Node.TEXT_NODE&&(b=EPUBJS.core.indexOfTextNode(a)+1,f.push("text()["+b+"]"),a=a.parentNode);a&&1==a.nodeType;a=a.parentNode){b=0;for(var h=a.previousSibling;h;h=h.previousSibling)h.nodeType!=Node.DOCUMENT_TYPE_NODE&&h.nodeName==a.nodeName&&++b;c=a.nodeName.toLowerCase(),d=g?"xhtml:"+c:c,e=b?"["+(b+1)+"]":"",f.splice(0,0,d+e)}return f.length?"./"+f.join("/"):null},EPUBJS.core.nsResolver=function(a){return{xhtml:"http://www.w3.org/1999/xhtml",epub:"http://www.idpf.org/2007/ops"}[a]||null},EPUBJS.core.cleanStringForXpath=function(a){var b=a.match(/[^'"]+|['"]/g);return b=b.map(function(a){return"'"===a?'"\'"':'"'===a?"'\"'":"'"+a+"'"}),"concat('',"+b.join(",")+")"},EPUBJS.core.indexOfTextNode=function(a){for(var b,c=a.parentNode,d=c.childNodes,e=-1,f=0;f<d.length&&(b=d[f],b.nodeType===Node.TEXT_NODE&&e++,b!=a);f++);return e},EPUBJS.core.defaults=function(a){for(var b=1,c=arguments.length;b<c;b++){var d=arguments[b];for(var e in d)void 0===a[e]&&(a[e]=d[e])}return a},EPUBJS.core.extend=function(a){return[].slice.call(arguments,1).forEach(function(b){b&&Object.getOwnPropertyNames(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))})}),a},EPUBJS.core.clone=function(a){return EPUBJS.core.isArray(a)?a.slice():EPUBJS.core.extend({},a)},EPUBJS.core.isElement=function(a){return!(!a||1!=a.nodeType)},EPUBJS.core.isNumber=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},EPUBJS.core.isString=function(a){return"string"==typeof a||a instanceof String},EPUBJS.core.isArray=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},EPUBJS.core.values=function(a){var b,c,d,e=-1;if(!a)return[];for(b=Object.keys(a),c=b.length,d=Array(c);++e<c;)d[e]=a[b[e]];return d},EPUBJS.core.indexOfNode=function(a,b){for(var c,d=a.parentNode,e=d.childNodes,f=-1,g=0;g<e.length&&(c=e[g],c.nodeType===b&&f++,c!=a);g++);return f},EPUBJS.core.indexOfTextNode=function(a){return EPUBJS.core.indexOfNode(a,TEXT_NODE)},EPUBJS.core.indexOfElementNode=function(a){return EPUBJS.core.indexOfNode(a,ELEMENT_NODE)};var EPUBJS=EPUBJS||{};EPUBJS.reader={},EPUBJS.reader.plugins={},function(a,b){var c=(a.ePubReader,a.ePubReader=function(a,b){return new EPUBJS.Reader(a,b)});"function"==typeof define&&define.amd?define(function(){return Reader}):"undefined"!=typeof module&&module.exports&&(module.exports=c)}(window,jQuery),EPUBJS.Reader=function(a,b){var c,d,e,f=this,g=$("#viewer"),h=window.location.search;this.settings=EPUBJS.core.defaults(b||{},{bookPath:a,restore:!1,reload:!1,bookmarks:void 0,annotations:void 0,contained:void 0,bookKey:void 0,styles:void 0,sidebarReflow:!1,generatePagination:!1,history:!0}),h&&(e=h.slice(1).split("&"),e.forEach(function(a){var b=a.split("="),c=b[0],d=b[1]||"";f.settings[c]=decodeURIComponent(d)})),this.setBookKey(this.settings.bookPath),this.settings.restore&&this.isSaved()&&this.applySavedSettings(),this.settings.styles=this.settings.styles||{fontSize:"100%"},this.book=c=new ePub(this.settings.bookPath,this.settings),this.offline=!1,this.sidebarOpen=!1,this.settings.bookmarks||(this.settings.bookmarks=[]),this.settings.annotations||(this.settings.annotations=[]),this.settings.generatePagination&&c.generatePagination(g.width(),g.height()),this.rendition=c.renderTo("viewer",{ignoreClass:"annotator-hl",width:"100%",height:"100%"}),this.settings.previousLocationCfi?this.displayed=this.rendition.display(this.settings.previousLocationCfi):this.displayed=this.rendition.display(),c.ready.then(function(){f.ReaderController=EPUBJS.reader.ReaderController.call(f,c),f.SettingsController=EPUBJS.reader.SettingsController.call(f,c),f.ControlsController=EPUBJS.reader.ControlsController.call(f,c),f.SidebarController=EPUBJS.reader.SidebarController.call(f,c),f.BookmarksController=EPUBJS.reader.BookmarksController.call(f,c),f.NotesController=EPUBJS.reader.NotesController.call(f,c),window.addEventListener("hashchange",this.hashChanged.bind(this),!1),document.addEventListener("keydown",this.adjustFontSize.bind(this),!1),this.rendition.on("keydown",this.adjustFontSize.bind(this)),this.rendition.on("keydown",f.ReaderController.arrowKeys.bind(this)),this.rendition.on("selected",this.selectedRange.bind(this))}.bind(this)).then(function(){f.ReaderController.hideLoader()}.bind(this));for(d in EPUBJS.reader.plugins)EPUBJS.reader.plugins.hasOwnProperty(d)&&(f[d]=EPUBJS.reader.plugins[d].call(f,c));return c.loaded.metadata.then(function(a){f.MetaController=EPUBJS.reader.MetaController.call(f,a)}),c.loaded.navigation.then(function(a){f.TocController=EPUBJS.reader.TocController.call(f,a)}),window.addEventListener("beforeunload",this.unload.bind(this),!1),this},EPUBJS.Reader.prototype.adjustFontSize=function(a){var b,c=2,d=a.ctrlKey||a.metaKey;this.settings.styles&&(this.settings.styles.fontSize||(this.settings.styles.fontSize="100%"),b=parseInt(this.settings.styles.fontSize.slice(0,-1)),d&&187==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize",b+c+"%")),d&&189==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize",b-c+"%")),d&&48==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize","100%")))},EPUBJS.Reader.prototype.addBookmark=function(a){this.isBookmarked(a)>-1||(this.settings.bookmarks.push(a),this.trigger("reader:bookmarked",a))},EPUBJS.Reader.prototype.removeBookmark=function(a){var b=this.isBookmarked(a);-1!==b&&(this.settings.bookmarks.splice(b,1),this.trigger("reader:unbookmarked",b))},EPUBJS.Reader.prototype.isBookmarked=function(a){return this.settings.bookmarks.indexOf(a)},EPUBJS.Reader.prototype.clearBookmarks=function(){this.settings.bookmarks=[]},EPUBJS.Reader.prototype.addNote=function(a){this.settings.annotations.push(a)},EPUBJS.Reader.prototype.removeNote=function(a){var b=this.settings.annotations.indexOf(a);-1!==b&&delete this.settings.annotations[b]},EPUBJS.Reader.prototype.clearNotes=function(){this.settings.annotations=[]},EPUBJS.Reader.prototype.setBookKey=function(a){return this.settings.bookKey||(this.settings.bookKey="epubjsreader:"+EPUBJS.VERSION+":"+window.location.host+":"+a),this.settings.bookKey},EPUBJS.Reader.prototype.isSaved=function(a){return!!localStorage&&null!==localStorage.getItem(this.settings.bookKey)},EPUBJS.Reader.prototype.removeSavedSettings=function(){if(!localStorage)return!1;localStorage.removeItem(this.settings.bookKey)},EPUBJS.Reader.prototype.applySavedSettings=function(){var a;if(!localStorage)return!1;try{a=JSON.parse(localStorage.getItem(this.settings.bookKey))}catch(a){return!1}return!!a&&(a.styles&&(this.settings.styles=EPUBJS.core.defaults(this.settings.styles||{},a.styles)),this.settings=EPUBJS.core.defaults(this.settings,a),!0)},EPUBJS.Reader.prototype.saveSettings=function(){if(this.book&&(this.settings.previousLocationCfi=this.rendition.currentLocation().start.cfi),!localStorage)return!1;localStorage.setItem(this.settings.bookKey,JSON.stringify(this.settings))},EPUBJS.Reader.prototype.unload=function(){this.settings.restore&&localStorage&&this.saveSettings()},EPUBJS.Reader.prototype.hashChanged=function(){var a=window.location.hash.slice(1);this.rendition.display(a)},EPUBJS.Reader.prototype.selectedRange=function(a){var b="#"+a;this.settings.history&&window.location.hash!=b&&(history.pushState({},"",b),this.currentLocationCfi=a)},RSVP.EventTarget.mixin(EPUBJS.Reader.prototype),EPUBJS.reader.BookmarksController=function(){var a=this.book,b=this.rendition,c=$("#bookmarksView"),d=c.find("#bookmarks"),e=document.createDocumentFragment(),f=function(){c.show()},g=function(){c.hide()},h=0,i=function(c){var d=document.createElement("li"),e=document.createElement("a");d.id="bookmark-"+h,d.classList.add("list_item");var f,g=a.spine.get(c);return g.index in a.navigation.toc?(f=a.navigation.toc[g.index],e.textContent=f.label):e.textContent=c,e.href=c,e.classList.add("bookmark_link"),e.addEventListener("click",function(a){var c=this.getAttribute("href");b.display(c),a.preventDefault()},!1),d.appendChild(e),h++,d};return this.settings.bookmarks.forEach(function(a){var b=i(a);e.appendChild(b)}),d.append(e),this.on("reader:bookmarked",function(a){var b=i(a);d.append(b)}),this.on("reader:unbookmarked",function(a){$("#bookmark-"+a).remove()}),{show:f,hide:g}},EPUBJS.reader.ControlsController=function(a){var b=this,c=this.rendition,d=($("#store"),$("#fullscreen")),e=($("#fullscreenicon"),$("#cancelfullscreenicon"),$("#slider")),f=($("#main"),$("#sidebar"),$("#setting")),g=$("#bookmark");return e.on("click",function(){b.sidebarOpen?(b.SidebarController.hide(),e.addClass("icon-menu"),e.removeClass("icon-right")):(b.SidebarController.show(),e.addClass("icon-right"),e.removeClass("icon-menu"))}),"undefined"!=typeof screenfull&&(d.on("click",function(){screenfull.toggle($("#container")[0])}),screenfull.raw&&document.addEventListener(screenfull.raw.fullscreenchange,function(){fullscreen=screenfull.isFullscreen,fullscreen?d.addClass("icon-resize-small").removeClass("icon-resize-full"):d.addClass("icon-resize-full").removeClass("icon-resize-small")})),f.on("click",function(){b.SettingsController.show()}),g.on("click",function(){var a=b.rendition.currentLocation().start.cfi;-1===b.isBookmarked(a)?(b.addBookmark(a),g.addClass("icon-bookmark").removeClass("icon-bookmark-empty")):(b.removeBookmark(a),g.removeClass("icon-bookmark").addClass("icon-bookmark-empty"))}),c.on("relocated",function(a){var c=a.start.cfi,d="#"+c;-1===b.isBookmarked(c)?g.removeClass("icon-bookmark").addClass("icon-bookmark-empty"):g.addClass("icon-bookmark").removeClass("icon-bookmark-empty"),b.currentLocationCfi=c,b.settings.history&&window.location.hash!=d&&history.pushState({},"",d)}),{}},EPUBJS.reader.MetaController=function(a){var b=a.title,c=a.creator,d=$("#book-title"),e=$("#chapter-title"),f=$("#title-seperator");document.title=b+" – "+c,d.html(b),e.html(c),f.show()},EPUBJS.reader.NotesController=function(){var a=this.book,b=this.rendition,c=this,d=$("#notesView"),e=$("#notes"),f=$("#note-text"),g=$("#note-anchor"),h=c.settings.annotations,i=a.renderer,j=[],k=new ePub.CFI,l=function(){d.show()},m=function(){d.hide()},n=function(d){var e,h,i,j,l,m=a.renderer.doc;if(m.caretPositionFromPoint?(e=m.caretPositionFromPoint(d.clientX,d.clientY),h=e.offsetNode,i=e.offset):m.caretRangeFromPoint&&(e=m.caretRangeFromPoint(d.clientX,d.clientY),h=e.startContainer,i=e.startOffset),3!==h.nodeType)for(var q=0;q<h.childNodes.length;q++)if(3==h.childNodes[q].nodeType){h=h.childNodes[q];break}i=h.textContent.indexOf(".",i),-1===i?i=h.length:i+=1,j=k.generateCfiFromTextNode(h,i,a.renderer.currentChapter.cfiBase),l={annotatedAt:new Date,anchor:j,body:f.val()},c.addNote(l),o(l),p(l),f.val(""),g.text("Attach"),f.prop("disabled",!1),b.off("click",n)},o=function(a){var c=document.createElement("li"),d=document.createElement("a");c.innerHTML=a.body,d.innerHTML=" context »",d.href="#"+a.anchor,d.onclick=function(){return b.display(a.anchor),!1},c.appendChild(d),e.append(c)},p=function(b){var c=a.renderer.doc,d=document.createElement("span"),e=document.createElement("a");d.classList.add("footnotesuperscript","reader_generated"),d.style.verticalAlign="super",d.style.fontSize=".75em",d.style.lineHeight="1em",e.style.padding="2px",e.style.backgroundColor="#fffa96",e.style.borderRadius="5px",e.style.cursor="pointer",d.id="note-"+EPUBJS.core.uuid(),e.innerHTML=h.indexOf(b)+1+"[Reader]",d.appendChild(e),k.addMarker(b.anchor,c,d),q(d,b.body)},q=function(a,d){var e=a.id,f=function(){var c,f,l,m,n=i.height,o=i.width,p=225;j[e]||(j[e]=document.createElement("div"),j[e].setAttribute("class","popup"),pop_content=document.createElement("div"),j[e].appendChild(pop_content),pop_content.innerHTML=d,pop_content.setAttribute("class","pop_content"),i.render.document.body.appendChild(j[e]),j[e].addEventListener("mouseover",g,!1),j[e].addEventListener("mouseout",h,!1),b.on("locationChanged",k,this),b.on("locationChanged",h,this)),c=j[e],f=a.getBoundingClientRect(),l=f.left,m=f.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=l-popRect.width/2+"px",c.style.top=m+"px",p>n/2.5&&(p=n/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+m>=n-25?(c.style.top=m-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),l-popRect.width<=0?(c.style.left=l+"px",c.classList.add("left")):c.classList.remove("left"),l+popRect.width/2>=o?(c.style.left=l-300+"px",popRect=c.getBoundingClientRect(),c.style.left=l-popRect.width+"px",popRect.height+m>=n-25?(c.style.top=m-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")},g=function(){j[e].classList.add("on")},h=function(){j[e].classList.remove("on")},k=function(){setTimeout(function(){j[e].classList.remove("show")},100)},m=function(){c.ReaderController.slideOut(),l()};a.addEventListener("mouseover",f,!1),a.addEventListener("mouseout",k,!1),a.addEventListener("click",m,!1)};return g.on("click",function(a){g.text("Cancel"),f.prop("disabled","true"),b.on("click",n)}),h.forEach(function(a){o(a)}),{show:l,hide:m}},EPUBJS.reader.ReaderController=function(a){var b=$("#main"),c=$("#divider"),d=$("#loader"),e=$("#next"),f=$("#prev"),g=this,a=this.book,h=this.rendition,i=function(){h.currentLocation().start.cfi;g.settings.sidebarReflow?(b.removeClass("single"),b.one("transitionend",function(){h.resize()})):b.removeClass("closed")},j=function(){var a=h.currentLocation();if(a){a.start.cfi;g.settings.sidebarReflow?(b.addClass("single"),b.one("transitionend",function(){h.resize()})):b.addClass("closed")}},k=function(){d.show(),n()},l=function(){d.hide()},m=function(){c.addClass("show")},n=function(){c.removeClass("show")},o=!1,p=function(b){37==b.keyCode&&("rtl"===a.package.metadata.direction?h.next():h.prev(),f.addClass("active"),o=!0,setTimeout(function(){o=!1,f.removeClass("active")},100),b.preventDefault()),39==b.keyCode&&("rtl"===a.package.metadata.direction?h.prev():h.next(),e.addClass("active"),o=!0,setTimeout(function(){o=!1,e.removeClass("active")},100),b.preventDefault())};return document.addEventListener("keydown",p,!1),e.on("click",function(b){"rtl"===a.package.metadata.direction?h.prev():h.next(),b.preventDefault()}),f.on("click",function(b){"rtl"===a.package.metadata.direction?h.next():h.prev(),b.preventDefault()}),h.on("layout",function(a){!0===a.spread?m():n()}),h.on("relocated",function(a){a.atStart&&f.addClass("disabled"),a.atEnd&&e.addClass("disabled")}),{slideOut:j,slideIn:i,showLoader:k,hideLoader:l,showDivider:m,hideDivider:n,arrowKeys:p}},EPUBJS.reader.SettingsController=function(){var a=(this.book,this),b=$("#settings-modal"),c=$(".overlay"),d=function(){b.addClass("md-show")},e=function(){b.removeClass("md-show")};return $("#sidebarReflow").on("click",function(){a.settings.sidebarReflow=!a.settings.sidebarReflow}),b.find(".closer").on("click",function(){e()}),c.on("click",function(){e()}),{show:d,hide:e}},EPUBJS.reader.SidebarController=function(a){var b=this,c=$("#sidebar"),d=$("#panels"),e="Toc",f=function(a){var c=a+"Controller";e!=a&&void 0!==b[c]&&(b[e+"Controller"].hide(),b[c].show(),e=a,d.find(".active").removeClass("active"),d.find("#show-"+a).addClass("active"))},g=function(){return e},h=function(){b.sidebarOpen=!0,b.ReaderController.slideOut(),c.addClass("open")},i=function(){b.sidebarOpen=!1,b.ReaderController.slideIn(),c.removeClass("open")};return d.find(".show_view").on("click",function(a){var b=$(this).data("view");f(b),a.preventDefault()}),{show:h,hide:i,getActivePanel:g,changePanelTo:f}},EPUBJS.reader.TocController=function(a){var b=(this.book,this.rendition),c=$("#tocView"),d=document.createDocumentFragment(),e=!1,f=function(a,b){var c=document.createElement("ul");return b||(b=1),a.forEach(function(a){var d=document.createElement("li"),e=document.createElement("a");toggle=document.createElement("a");var g;d.id="toc-"+a.id,d.classList.add("list_item"),e.textContent=a.label,e.href=a.href,e.classList.add("toc_link"),d.appendChild(e),a.subitems&&a.subitems.length>0&&(b++,g=f(a.subitems,b),toggle.classList.add("toc_toggle"),d.insertBefore(toggle,e),d.appendChild(g)),c.appendChild(d)}),c},g=function(){c.show()},h=function(){c.hide()},i=function(a){var b=a.id,d=c.find("#toc-"+b),f=c.find(".currentChapter");c.find(".openChapter");d.length&&(d!=f&&d.has(e).length>0&&f.removeClass("currentChapter"),d.addClass("currentChapter"),d.parents("li").addClass("openChapter"))};b.on("renderered",i);var j=f(a);return d.appendChild(j),c.append(d),c.find(".toc_link").on("click",function(a){var d=this.getAttribute("href");a.preventDefault(),b.display(d),c.find(".currentChapter").addClass("openChapter").removeClass("currentChapter"),$(this).parent("li").addClass("currentChapter")}),c.find(".toc_toggle").on("click",function(a){var b=$(this).parent("li"),c=b.hasClass("openChapter");a.preventDefault(),c?b.removeClass("openChapter"):b.addClass("openChapter")}),{show:g,hide:h}}; | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/reader.min.js | reader.min.js |
EPUBJS.Hooks.register("beforeChapterDisplay").endnotes=function(a,b){var c=b.contents.querySelectorAll("a[href]"),d=Array.prototype.slice.call(c),e=EPUBJS.core.folder(location.pathname),f=(EPUBJS.cssPath,{});EPUBJS.core.addCss(EPUBJS.cssPath+"popup.css",!1,b.render.document.head),d.forEach(function(a){function c(){var c,h,n=b.height,o=b.width,p=225;m||(c=j.cloneNode(!0),m=c.querySelector("p")),f[i]||(f[i]=document.createElement("div"),f[i].setAttribute("class","popup"),pop_content=document.createElement("div"),f[i].appendChild(pop_content),pop_content.appendChild(m),pop_content.setAttribute("class","pop_content"),b.render.document.body.appendChild(f[i]),f[i].addEventListener("mouseover",d,!1),f[i].addEventListener("mouseout",e,!1),b.on("renderer:pageChanged",g,this),b.on("renderer:pageChanged",e,this)),c=f[i],h=a.getBoundingClientRect(),k=h.left,l=h.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=k-popRect.width/2+"px",c.style.top=l+"px",p>n/2.5&&(p=n/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+l>=n-25?(c.style.top=l-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),k-popRect.width<=0?(c.style.left=k+"px",c.classList.add("left")):c.classList.remove("left"),k+popRect.width/2>=o?(c.style.left=k-300+"px",popRect=c.getBoundingClientRect(),c.style.left=k-popRect.width+"px",popRect.height+l>=n-25?(c.style.top=l-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")}function d(){f[i].classList.add("on")}function e(){f[i].classList.remove("on")}function g(){setTimeout(function(){f[i].classList.remove("show")},100)}var h,i,j,k,l,m;"noteref"==a.getAttribute("epub:type")&&(h=a.getAttribute("href"),i=h.replace("#",""),j=b.render.document.getElementById(i),a.addEventListener("mouseover",c,!1),a.addEventListener("mouseout",g,!1))}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").mathml=function(a,b){if(b.currentChapter.manifestProperties.indexOf("mathml")!==-1){b.render.iframe.contentWindow.mathmlCallback=a;var c=document.createElement("script");c.type="text/x-mathjax-config",c.innerHTML=' MathJax.Hub.Register.StartupHook("End",function () { window.mathmlCallback(); }); MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); ',b.doc.body.appendChild(c),EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",null,b.doc.head)}else a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").smartimages=function(a,b){var c=b.contents.querySelectorAll("img"),d=Array.prototype.slice.call(c),e=b.height;if("reflowable"!=b.layoutSettings.layout)return void a();d.forEach(function(a){var c=function(){var c,d=a.getBoundingClientRect(),f=d.height,g=d.top,h=a.getAttribute("data-height"),i=h||f,j=Number(getComputedStyle(a,"").fontSize.match(/(\d*(\.\d*)?)px/)[1]),k=j?j/2:0;e=b.contents.clientHeight,g<0&&(g=0),a.style.maxWidth="100%",i+g>=e?(g<e/2?(c=e-g-k,a.style.maxHeight=c+"px",a.style.width="auto"):(i>e&&(a.style.maxHeight=e+"px",a.style.width="auto",d=a.getBoundingClientRect(),i=d.height),a.style.display="block",a.style.WebkitColumnBreakBefore="always",a.style.breakBefore="column"),a.setAttribute("data-height",c)):(a.style.removeProperty("max-height"),a.style.removeProperty("margin-top"))},d=function(){b.off("renderer:resized",c),b.off("renderer:chapterUnload",this)};a.addEventListener("load",c,!1),b.on("renderer:resized",c),b.on("renderer:chapterUnload",d),c()}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").transculsions=function(a,b){var c=b.contents.querySelectorAll("[transclusion]");Array.prototype.slice.call(c).forEach(function(a){function c(){j=g,k=h,j>chapter.colWidth&&(d=chapter.colWidth/j,j=chapter.colWidth,k*=d),f.width=j,f.height=k}var d,e=a.getAttribute("ref"),f=document.createElement("iframe"),g=a.getAttribute("width"),h=a.getAttribute("height"),i=a.parentNode,j=g,k=h;c(),b.listenUntil("renderer:resized","renderer:chapterUnloaded",c),f.src=e,i.replaceChild(f,a)}),a&&a()}; | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/hooks.min.js | hooks.min.js |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.RSVP = global.RSVP || {})));
}(this, (function (exports) { 'use strict';
function indexOf(callbacks, callback) {
for (var i = 0, l = callbacks.length; i < l; i++) {
if (callbacks[i] === callback) {
return i;
}
}
return -1;
}
function callbacksFor(object) {
var callbacks = object._promiseCallbacks;
if (!callbacks) {
callbacks = object._promiseCallbacks = {};
}
return callbacks;
}
/**
@class RSVP.EventTarget
*/
var EventTarget = {
/**
`RSVP.EventTarget.mixin` extends an object with EventTarget methods. For
Example:
```javascript
let object = {};
RSVP.EventTarget.mixin(object);
object.on('finished', function(event) {
// handle event
});
object.trigger('finished', { detail: value });
```
`EventTarget.mixin` also works with prototypes:
```javascript
let Person = function() {};
RSVP.EventTarget.mixin(Person.prototype);
let yehuda = new Person();
let tom = new Person();
yehuda.on('poke', function(event) {
console.log('Yehuda says OW');
});
tom.on('poke', function(event) {
console.log('Tom says OW');
});
yehuda.trigger('poke');
tom.trigger('poke');
```
@method mixin
@for RSVP.EventTarget
@private
@param {Object} object object to extend with EventTarget methods
*/
mixin: function (object) {
object['on'] = this['on'];
object['off'] = this['off'];
object['trigger'] = this['trigger'];
object._promiseCallbacks = undefined;
return object;
},
/**
Registers a callback to be executed when `eventName` is triggered
```javascript
object.on('event', function(eventInfo){
// handle the event
});
object.trigger('event');
```
@method on
@for RSVP.EventTarget
@private
@param {String} eventName name of the event to listen for
@param {Function} callback function to be called when the event is triggered.
*/
on: function (eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}
var allCallbacks = callbacksFor(this),
callbacks = void 0;
callbacks = allCallbacks[eventName];
if (!callbacks) {
callbacks = allCallbacks[eventName] = [];
}
if (indexOf(callbacks, callback) === -1) {
callbacks.push(callback);
}
},
/**
You can use `off` to stop firing a particular callback for an event:
```javascript
function doStuff() { // do stuff! }
object.on('stuff', doStuff);
object.trigger('stuff'); // doStuff will be called
// Unregister ONLY the doStuff callback
object.off('stuff', doStuff);
object.trigger('stuff'); // doStuff will NOT be called
```
If you don't pass a `callback` argument to `off`, ALL callbacks for the
event will not be executed when the event fires. For example:
```javascript
let callback1 = function(){};
let callback2 = function(){};
object.on('stuff', callback1);
object.on('stuff', callback2);
object.trigger('stuff'); // callback1 and callback2 will be executed.
object.off('stuff');
object.trigger('stuff'); // callback1 and callback2 will not be executed!
```
@method off
@for RSVP.EventTarget
@private
@param {String} eventName event to stop listening to
@param {Function} callback optional argument. If given, only the function
given will be removed from the event's callback queue. If no `callback`
argument is given, all callbacks will be removed from the event's callback
queue.
*/
off: function (eventName, callback) {
var allCallbacks = callbacksFor(this),
callbacks = void 0,
index = void 0;
if (!callback) {
allCallbacks[eventName] = [];
return;
}
callbacks = allCallbacks[eventName];
index = indexOf(callbacks, callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
},
/**
Use `trigger` to fire custom events. For example:
```javascript
object.on('foo', function(){
console.log('foo event happened!');
});
object.trigger('foo');
// 'foo event happened!' logged to the console
```
You can also pass a value as a second argument to `trigger` that will be
passed as an argument to all event listeners for the event:
```javascript
object.on('foo', function(value){
console.log(value.name);
});
object.trigger('foo', { name: 'bar' });
// 'bar' logged to the console
```
@method trigger
@for RSVP.EventTarget
@private
@param {String} eventName name of the event to be triggered
@param {*} options optional value to be passed to any event handlers for
the given `eventName`
*/
trigger: function (eventName, options, label) {
var allCallbacks = callbacksFor(this),
callbacks = void 0,
callback = void 0;
if (callbacks = allCallbacks[eventName]) {
// Don't cache the callbacks.length since it may grow
for (var i = 0; i < callbacks.length; i++) {
callback = callbacks[i];
callback(options, label);
}
}
}
};
var config = {
instrument: false
};
EventTarget['mixin'](config);
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
function isObject(x) {
return x !== null && typeof x === 'object';
}
function isMaybeThenable(x) {
return x !== null && typeof x === 'object';
}
var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function () {
return new Date().getTime();
};
var queue = [];
function scheduleFlush() {
setTimeout(function () {
for (var i = 0; i < queue.length; i++) {
var entry = queue[i];
var payload = entry.payload;
payload.guid = payload.key + payload.id;
payload.childGuid = payload.key + payload.childId;
if (payload.error) {
payload.stack = payload.error.stack;
}
config['trigger'](entry.name, entry.payload);
}
queue.length = 0;
}, 50);
}
function instrument(eventName, promise, child) {
if (1 === queue.push({
name: eventName,
payload: {
key: promise._guidKey,
id: promise._id,
eventName: eventName,
detail: promise._result,
childId: child && child._id,
label: promise._label,
timeStamp: now(),
error: config["instrument-with-stack"] ? new Error(promise._label) : null
} })) {
scheduleFlush();
}
}
/**
`RSVP.Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new RSVP.Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = RSVP.Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {*} object value that the returned promise will be resolved with
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object, label) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop, label);
resolve(promise, object);
return promise;
}
function withOwnPromise() {
return new TypeError('A promises callback cannot return that same promise.');
}
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
config.async(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value, undefined);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
thenable._onError = null;
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
if (thenable !== value) {
resolve(promise, value, undefined);
} else {
fulfill(promise, value);
}
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
var isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$1;
if (isOwnThenable) {
handleOwnThenable(promise, maybeThenable);
} else if (then$$1 === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
GET_THEN_ERROR.error = null;
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onError) {
promise._onError(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length === 0) {
if (config.instrument) {
instrument('fulfilled', promise);
}
} else {
config.async(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
config.async(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onError = null;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
config.async(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (config.instrument) {
instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);
}
if (subscribers.length === 0) {
return;
}
var child = void 0,
callback = void 0,
result = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, result);
} else {
callback(result);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, result) {
try {
return callback(result);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(state, promise, callback, result) {
var hasCallback = isFunction(callback);
var value = void 0,
error = void 0;
if (hasCallback) {
value = tryCatch(callback, result);
if (value === TRY_CATCH_ERROR) {
error = value.error;
value.error = null; // release
} else if (value === promise) {
reject(promise, withOwnPromise());
return;
}
} else {
value = result;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && error === undefined) {
resolve(promise, value);
} else if (error !== undefined) {
reject(promise, error);
} else if (state === FULFILLED) {
fulfill(promise, value);
} else if (state === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
var resolved = false;
try {
resolver(function (value) {
if (resolved) {
return;
}
resolved = true;
resolve(promise, value);
}, function (reason) {
if (resolved) {
return;
}
resolved = true;
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
function then(onFulfillment, onRejection, label) {
var parent = this;
var state = parent._state;
if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
config.instrument && instrument('chained', parent, parent);
return parent;
}
parent._onError = null;
var child = new parent.constructor(noop, label);
var result = parent._result;
config.instrument && instrument('chained', parent, child);
if (state === PENDING) {
subscribe(parent, child, onFulfillment, onRejection);
} else {
var callback = state === FULFILLED ? onFulfillment : onRejection;
config.async(function () {
return invokeCallback(state, child, callback, result);
});
}
return child;
}
var Enumerator = function () {
function Enumerator(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop, label);
this._abortOnReject = abortOnReject;
this._init.apply(this, arguments);
}
Enumerator.prototype._init = function _init(Constructor, input) {
var len = input.length || 0;
this.length = len;
this._remaining = len;
this._result = new Array(len);
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
};
Enumerator.prototype._enumerate = function _enumerate(input) {
var length = this.length;
var promise = this.promise;
for (var i = 0; promise._state === PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator.prototype._settleMaybeThenable = function _settleMaybeThenable(entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var then$$1 = getThen(entry);
if (then$$1 === then && entry._state !== PENDING) {
entry._onError = null;
this._settledAt(entry._state, i, entry._result);
} else if (typeof then$$1 !== 'function') {
this._remaining--;
this._result[i] = this._makeResult(FULFILLED, i, entry);
} else if (c === Promise) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, then$$1);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
if (isMaybeThenable(entry)) {
this._settleMaybeThenable(entry, i);
} else {
this._remaining--;
this._result[i] = this._makeResult(FULFILLED, i, entry);
}
};
Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
if (this._abortOnReject && state === REJECTED) {
reject(promise, value);
} else {
this._remaining--;
this._result[i] = this._makeResult(state, i, value);
if (this._remaining === 0) {
fulfill(promise, this._result);
}
}
}
};
Enumerator.prototype._makeResult = function _makeResult(state, i, value) {
return value;
};
Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
return Enumerator;
}();
function makeSettledResult(state, position, value) {
if (state === FULFILLED) {
return {
state: 'fulfilled',
value: value
};
} else {
return {
state: 'rejected',
reason: value
};
}
}
/**
`RSVP.Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = RSVP.resolve(1);
let promise2 = RSVP.resolve(2);
let promise3 = RSVP.resolve(3);
let promises = [ promise1, promise2, promise3 ];
RSVP.Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = RSVP.resolve(1);
let promise2 = RSVP.reject(new Error("2"));
let promise3 = RSVP.reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
RSVP.Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries, label) {
if (!isArray(entries)) {
return this.reject(new TypeError("Promise.all must be called with an array"), label);
}
return new Enumerator(this, entries, true /* abort on reject */, label).promise;
}
/**
`RSVP.Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
RSVP.Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`RSVP.Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
RSVP.Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
RSVP.Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} entries array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop, label);
if (!isArray(entries)) {
reject(promise, new TypeError('Promise.race must be called with an array'));
return promise;
}
for (var i = 0; promise._state === PENDING && i < entries.length; i++) {
subscribe(Constructor.resolve(entries[i]), undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
return promise;
}
/**
`RSVP.Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = RSVP.Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {*} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop, label);
reject(promise, reason);
return promise;
}
var guidKey = 'rsvp_' + now() + '-';
var counter = 0;
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise’s eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class RSVP.Promise
@param {function} resolver
@param {String} label optional string for labeling the promise.
Useful for tooling.
@constructor
*/
var Promise = function () {
function Promise(resolver, label) {
this._id = counter++;
this._label = label;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
config.instrument && instrument('created', this);
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
Promise.prototype._onError = function _onError(reason) {
var _this = this;
config.after(function () {
if (_this._onError) {
config.trigger('error', reason, _this._label);
}
});
};
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn\'t find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
Promise.prototype.catch = function _catch(onRejection, label) {
return this.then(undefined, onRejection, label);
};
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuthor();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuthor();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
Promise.prototype.finally = function _finally(callback, label) {
var promise = this;
var constructor = promise.constructor;
return promise.then(function (value) {
return constructor.resolve(callback()).then(function () {
return value;
});
}, function (reason) {
return constructor.resolve(callback()).then(function () {
throw reason;
});
}, label);
};
return Promise;
}();
Promise.cast = resolve$1; // deprecated
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve$1;
Promise.reject = reject$1;
Promise.prototype._guidKey = guidKey;
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we\'re unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfillment
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
Promise.prototype.then = then;
function Result() {
this.value = undefined;
}
var ERROR = new Result();
var GET_THEN_ERROR$1 = new Result();
function getThen$1(obj) {
try {
return obj.then;
} catch (error) {
ERROR.value = error;
return ERROR;
}
}
function tryApply(f, s, a) {
try {
f.apply(s, a);
} catch (error) {
ERROR.value = error;
return ERROR;
}
}
function makeObject(_, argumentNames) {
var obj = {};
var length = _.length;
var args = new Array(length);
for (var x = 0; x < length; x++) {
args[x] = _[x];
}
for (var i = 0; i < argumentNames.length; i++) {
var name = argumentNames[i];
obj[name] = args[i + 1];
}
return obj;
}
function arrayResult(_) {
var length = _.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = _[i];
}
return args;
}
function wrapThenable(then, promise) {
return {
then: function (onFulFillment, onRejection) {
return then.call(promise, onFulFillment, onRejection);
}
};
}
/**
`RSVP.denodeify` takes a 'node-style' function and returns a function that
will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the
browser when you'd prefer to use promises over using callbacks. For example,
`denodeify` transforms the following:
```javascript
let fs = require('fs');
fs.readFile('myfile.txt', function(err, data){
if (err) return handleError(err);
handleData(data);
});
```
into:
```javascript
let fs = require('fs');
let readFile = RSVP.denodeify(fs.readFile);
readFile('myfile.txt').then(handleData, handleError);
```
If the node function has multiple success parameters, then `denodeify`
just returns the first one:
```javascript
let request = RSVP.denodeify(require('request'));
request('http://example.com').then(function(res) {
// ...
});
```
However, if you need all success parameters, setting `denodeify`'s
second parameter to `true` causes it to return all success parameters
as an array:
```javascript
let request = RSVP.denodeify(require('request'), true);
request('http://example.com').then(function(result) {
// result[0] -> res
// result[1] -> body
});
```
Or if you pass it an array with names it returns the parameters as a hash:
```javascript
let request = RSVP.denodeify(require('request'), ['res', 'body']);
request('http://example.com').then(function(result) {
// result.res
// result.body
});
```
Sometimes you need to retain the `this`:
```javascript
let app = require('express')();
let render = RSVP.denodeify(app.render.bind(app));
```
The denodified function inherits from the original function. It works in all
environments, except IE 10 and below. Consequently all properties of the original
function are available to you. However, any properties you change on the
denodeified function won't be changed on the original function. Example:
```javascript
let request = RSVP.denodeify(require('request')),
cookieJar = request.jar(); // <- Inheritance is used here
request('http://example.com', {jar: cookieJar}).then(function(res) {
// cookieJar.cookies holds now the cookies returned by example.com
});
```
Using `denodeify` makes it easier to compose asynchronous operations instead
of using callbacks. For example, instead of:
```javascript
let fs = require('fs');
fs.readFile('myfile.txt', function(err, data){
if (err) { ... } // Handle error
fs.writeFile('myfile2.txt', data, function(err){
if (err) { ... } // Handle error
console.log('done')
});
});
```
you can chain the operations together using `then` from the returned promise:
```javascript
let fs = require('fs');
let readFile = RSVP.denodeify(fs.readFile);
let writeFile = RSVP.denodeify(fs.writeFile);
readFile('myfile.txt').then(function(data){
return writeFile('myfile2.txt', data);
}).then(function(){
console.log('done')
}).catch(function(error){
// Handle error
});
```
@method denodeify
@static
@for RSVP
@param {Function} nodeFunc a 'node-style' function that takes a callback as
its last argument. The callback expects an error to be passed as its first
argument (if an error occurred, otherwise null), and the value from the
operation as its second argument ('function(err, value){ }').
@param {Boolean|Array} [options] An optional paramter that if set
to `true` causes the promise to fulfill with the callback's success arguments
as an array. This is useful if the node function has multiple success
paramters. If you set this paramter to an array with names, the promise will
fulfill with a hash with these names as keys and the success parameters as
values.
@return {Function} a function that wraps `nodeFunc` to return an
`RSVP.Promise`
@static
*/
function denodeify(nodeFunc, options) {
var fn = function () {
var self = this;
var l = arguments.length;
var args = new Array(l + 1);
var promiseInput = false;
for (var i = 0; i < l; ++i) {
var arg = arguments[i];
if (!promiseInput) {
// TODO: clean this up
promiseInput = needsPromiseInput(arg);
if (promiseInput === GET_THEN_ERROR$1) {
var p = new Promise(noop);
reject(p, GET_THEN_ERROR$1.value);
return p;
} else if (promiseInput && promiseInput !== true) {
arg = wrapThenable(promiseInput, arg);
}
}
args[i] = arg;
}
var promise = new Promise(noop);
args[l] = function (err, val) {
if (err) reject(promise, err);else if (options === undefined) resolve(promise, val);else if (options === true) resolve(promise, arrayResult(arguments));else if (isArray(options)) resolve(promise, makeObject(arguments, options));else resolve(promise, val);
};
if (promiseInput) {
return handlePromiseInput(promise, args, nodeFunc, self);
} else {
return handleValueInput(promise, args, nodeFunc, self);
}
};
fn.__proto__ = nodeFunc;
return fn;
}
function handleValueInput(promise, args, nodeFunc, self) {
var result = tryApply(nodeFunc, self, args);
if (result === ERROR) {
reject(promise, result.value);
}
return promise;
}
function handlePromiseInput(promise, args, nodeFunc, self) {
return Promise.all(args).then(function (args) {
var result = tryApply(nodeFunc, self, args);
if (result === ERROR) {
reject(promise, result.value);
}
return promise;
});
}
function needsPromiseInput(arg) {
if (arg && typeof arg === 'object') {
if (arg.constructor === Promise) {
return true;
} else {
return getThen$1(arg);
}
} else {
return false;
}
}
/**
This is a convenient alias for `RSVP.Promise.all`.
@method all
@static
@for RSVP
@param {Array} array Array of promises.
@param {String} label An optional label. This is useful
for tooling.
*/
function all$1(array, label) {
return Promise.all(array, label);
}
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var AllSettled = function (_Enumerator) {
_inherits(AllSettled, _Enumerator);
function AllSettled(Constructor, entries, label) {
return _possibleConstructorReturn(this, _Enumerator.call(this, Constructor, entries, false /* don't abort on reject */, label));
}
return AllSettled;
}(Enumerator);
AllSettled.prototype._makeResult = makeSettledResult;
/**
`RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing
a fail-fast method, it waits until all the promises have returned and
shows you all the results. This is useful if you want to handle multiple
promises' failure states together as a set.
Returns a promise that is fulfilled when all the given promises have been
settled. The return promise is fulfilled with an array of the states of
the promises passed into the `promises` array argument.
Each state object will either indicate fulfillment or rejection, and
provide the corresponding value or reason. The states will take one of
the following formats:
```javascript
{ state: 'fulfilled', value: value }
or
{ state: 'rejected', reason: reason }
```
Example:
```javascript
let promise1 = RSVP.Promise.resolve(1);
let promise2 = RSVP.Promise.reject(new Error('2'));
let promise3 = RSVP.Promise.reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
RSVP.allSettled(promises).then(function(array){
// array == [
// { state: 'fulfilled', value: 1 },
// { state: 'rejected', reason: Error },
// { state: 'rejected', reason: Error }
// ]
// Note that for the second item, reason.message will be '2', and for the
// third item, reason.message will be '3'.
}, function(error) {
// Not run. (This block would only be called if allSettled had failed,
// for instance if passed an incorrect argument type.)
});
```
@method allSettled
@static
@for RSVP
@param {Array} entries
@param {String} label - optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled with an array of the settled
states of the constituent promises.
*/
function allSettled(entries, label) {
if (!isArray(entries)) {
return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label);
}
return new AllSettled(Promise, entries, label).promise;
}
/**
This is a convenient alias for `RSVP.Promise.race`.
@method race
@static
@for RSVP
@param {Array} array Array of promises.
@param {String} label An optional label. This is useful
for tooling.
*/
function race$1(array, label) {
return Promise.race(array, label);
}
function _possibleConstructorReturn$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var hasOwnProperty = Object.prototype.hasOwnProperty;
var PromiseHash = function (_Enumerator) {
_inherits$1(PromiseHash, _Enumerator);
function PromiseHash(Constructor, object) {
var abortOnReject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var label = arguments[3];
return _possibleConstructorReturn$1(this, _Enumerator.call(this, Constructor, object, abortOnReject, label));
}
PromiseHash.prototype._init = function _init(Constructor, object) {
this._result = {};
this._enumerate(object);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
};
PromiseHash.prototype._enumerate = function _enumerate(input) {
var promise = this.promise;
var results = [];
for (var key in input) {
if (hasOwnProperty.call(input, key)) {
results.push({
position: key,
entry: input[key]
});
}
}
var length = results.length;
this._remaining = length;
var result = void 0;
for (var i = 0; promise._state === PENDING && i < length; i++) {
result = results[i];
this._eachEntry(result.entry, result.position);
}
};
return PromiseHash;
}(Enumerator);
/**
`RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array
for its `promises` argument.
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The returned promise
is fulfilled with a hash that has the same key names as the `promises` object
argument. If any of the values in the object are not promises, they will
simply be copied over to the fulfilled object.
Example:
```javascript
let promises = {
myPromise: RSVP.resolve(1),
yourPromise: RSVP.resolve(2),
theirPromise: RSVP.resolve(3),
notAPromise: 4
};
RSVP.hash(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: 1,
// yourPromise: 2,
// theirPromise: 3,
// notAPromise: 4
// }
});
````
If any of the `promises` given to `RSVP.hash` are rejected, the first promise
that is rejected will be given as the reason to the rejection handler.
Example:
```javascript
let promises = {
myPromise: RSVP.resolve(1),
rejectedPromise: RSVP.reject(new Error('rejectedPromise')),
anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')),
};
RSVP.hash(promises).then(function(hash){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === 'rejectedPromise'
});
```
An important note: `RSVP.hash` is intended for plain JavaScript objects that
are just a set of keys and values. `RSVP.hash` will NOT preserve prototype
chains.
Example:
```javascript
function MyConstructor(){
this.example = RSVP.resolve('Example');
}
MyConstructor.prototype = {
protoProperty: RSVP.resolve('Proto Property')
};
let myObject = new MyConstructor();
RSVP.hash(myObject).then(function(hash){
// protoProperty will not be present, instead you will just have an
// object that looks like:
// {
// example: 'Example'
// }
//
// hash.hasOwnProperty('protoProperty'); // false
// 'undefined' === typeof hash.protoProperty
});
```
@method hash
@static
@for RSVP
@param {Object} object
@param {String} label optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all properties of `promises`
have been fulfilled, or rejected if any of them become rejected.
*/
function hash(object, label) {
if (!isObject(object)) {
return Promise.reject(new TypeError("Promise.hash must be called with an object"), label);
}
return new PromiseHash(Promise, object, label).promise;
}
function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var HashSettled = function (_PromiseHash) {
_inherits$2(HashSettled, _PromiseHash);
function HashSettled(Constructor, object, label) {
return _possibleConstructorReturn$2(this, _PromiseHash.call(this, Constructor, object, false, label));
}
return HashSettled;
}(PromiseHash);
HashSettled.prototype._makeResult = makeSettledResult;
/**
`RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object
instead of an array for its `promises` argument.
Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method,
but like `RSVP.allSettled`, `hashSettled` waits until all the
constituent promises have returned and then shows you all the results
with their states and values/reasons. This is useful if you want to
handle multiple promises' failure states together as a set.
Returns a promise that is fulfilled when all the given promises have been
settled, or rejected if the passed parameters are invalid.
The returned promise is fulfilled with a hash that has the same key names as
the `promises` object argument. If any of the values in the object are not
promises, they will be copied over to the fulfilled object and marked with state
'fulfilled'.
Example:
```javascript
let promises = {
myPromise: RSVP.Promise.resolve(1),
yourPromise: RSVP.Promise.resolve(2),
theirPromise: RSVP.Promise.resolve(3),
notAPromise: 4
};
RSVP.hashSettled(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: { state: 'fulfilled', value: 1 },
// yourPromise: { state: 'fulfilled', value: 2 },
// theirPromise: { state: 'fulfilled', value: 3 },
// notAPromise: { state: 'fulfilled', value: 4 }
// }
});
```
If any of the `promises` given to `RSVP.hash` are rejected, the state will
be set to 'rejected' and the reason for rejection provided.
Example:
```javascript
let promises = {
myPromise: RSVP.Promise.resolve(1),
rejectedPromise: RSVP.Promise.reject(new Error('rejection')),
anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')),
};
RSVP.hashSettled(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: { state: 'fulfilled', value: 1 },
// rejectedPromise: { state: 'rejected', reason: Error },
// anotherRejectedPromise: { state: 'rejected', reason: Error },
// }
// Note that for rejectedPromise, reason.message == 'rejection',
// and for anotherRejectedPromise, reason.message == 'more rejection'.
});
```
An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that
are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype
chains.
Example:
```javascript
function MyConstructor(){
this.example = RSVP.Promise.resolve('Example');
}
MyConstructor.prototype = {
protoProperty: RSVP.Promise.resolve('Proto Property')
};
let myObject = new MyConstructor();
RSVP.hashSettled(myObject).then(function(hash){
// protoProperty will not be present, instead you will just have an
// object that looks like:
// {
// example: { state: 'fulfilled', value: 'Example' }
// }
//
// hash.hasOwnProperty('protoProperty'); // false
// 'undefined' === typeof hash.protoProperty
});
```
@method hashSettled
@for RSVP
@param {Object} object
@param {String} label optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when when all properties of `promises`
have been settled.
@static
*/
function hashSettled(object, label) {
if (!isObject(object)) {
return Promise.reject(new TypeError("RSVP.hashSettled must be called with an object"), label);
}
return new HashSettled(Promise, object, false, label).promise;
}
/**
`RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event
loop in order to aid debugging.
Promises A+ specifies that any exceptions that occur with a promise must be
caught by the promises implementation and bubbled to the last handler. For
this reason, it is recommended that you always specify a second rejection
handler function to `then`. However, `RSVP.rethrow` will throw the exception
outside of the promise, so it bubbles up to your console if in the browser,
or domain/cause uncaught exception in Node. `rethrow` will also throw the
error again so the error can be handled by the promise per the spec.
```javascript
function throws(){
throw new Error('Whoops!');
}
let promise = new RSVP.Promise(function(resolve, reject){
throws();
});
promise.catch(RSVP.rethrow).then(function(){
// Code here doesn't run because the promise became rejected due to an
// error!
}, function (err){
// handle the error here
});
```
The 'Whoops' error will be thrown on the next turn of the event loop
and you can watch for it in your console. You can also handle it using a
rejection handler given to `.then` or `.catch` on the returned promise.
@method rethrow
@static
@for RSVP
@param {Error} reason reason the promise became rejected.
@throws Error
@static
*/
function rethrow(reason) {
setTimeout(function () {
throw reason;
});
throw reason;
}
/**
`RSVP.defer` returns an object similar to jQuery's `$.Deferred`.
`RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s
interface. New code should use the `RSVP.Promise` constructor instead.
The object returned from `RSVP.defer` is a plain object with three properties:
* promise - an `RSVP.Promise`.
* reject - a function that causes the `promise` property on this object to
become rejected
* resolve - a function that causes the `promise` property on this object to
become fulfilled.
Example:
```javascript
let deferred = RSVP.defer();
deferred.resolve("Success!");
deferred.promise.then(function(value){
// value here is "Success!"
});
```
@method defer
@static
@for RSVP
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Object}
*/
function defer(label) {
var deferred = { resolve: undefined, reject: undefined };
deferred.promise = new Promise(function (resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
}, label);
return deferred;
}
/**
`RSVP.map` is similar to JavaScript's native `map` method, except that it
waits for all promises to become fulfilled before running the `mapFn` on
each item in given to `promises`. `RSVP.map` returns a promise that will
become fulfilled with the result of running `mapFn` on the values the promises
become fulfilled with.
For example:
```javascript
let promise1 = RSVP.resolve(1);
let promise2 = RSVP.resolve(2);
let promise3 = RSVP.resolve(3);
let promises = [ promise1, promise2, promise3 ];
let mapFn = function(item){
return item + 1;
};
RSVP.map(promises, mapFn).then(function(result){
// result is [ 2, 3, 4 ]
});
```
If any of the `promises` given to `RSVP.map` are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
```javascript
let promise1 = RSVP.resolve(1);
let promise2 = RSVP.reject(new Error('2'));
let promise3 = RSVP.reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let mapFn = function(item){
return item + 1;
};
RSVP.map(promises, mapFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
```
`RSVP.map` will also wait if a promise is returned from `mapFn`. For example,
say you want to get all comments from a set of blog posts, but you need
the blog posts first because they contain a url to those comments.
```javscript
let mapFn = function(blogPost){
// getComments does some ajax and returns an RSVP.Promise that is fulfilled
// with some comments data
return getComments(blogPost.comments_url);
};
// getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled
// with some blog post data
RSVP.map(getBlogPosts(), mapFn).then(function(comments){
// comments is the result of asking the server for the comments
// of all blog posts returned from getBlogPosts()
});
```
@method map
@static
@for RSVP
@param {Array} promises
@param {Function} mapFn function to be called on each fulfilled promise.
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled with the result of calling
`mapFn` on each fulfilled promise or value when they become fulfilled.
The promise will be rejected if any of the given `promises` become rejected.
@static
*/
function map(promises, mapFn, label) {
if (!isArray(promises)) {
return Promise.reject(new TypeError("RSVP.map must be called with an array"), label);
}
if (!isFunction(mapFn)) {
return Promise.reject(new TypeError("RSVP.map expects a function as a second argument"), label);
}
return Promise.all(promises, label).then(function (values) {
var length = values.length;
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = mapFn(values[i]);
}
return Promise.all(results, label);
});
}
/**
This is a convenient alias for `RSVP.Promise.resolve`.
@method resolve
@static
@for RSVP
@param {*} value value that the returned promise will be resolved with
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$2(value, label) {
return Promise.resolve(value, label);
}
/**
This is a convenient alias for `RSVP.Promise.reject`.
@method reject
@static
@for RSVP
@param {*} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$2(reason, label) {
return Promise.reject(reason, label);
}
/**
`RSVP.filter` is similar to JavaScript's native `filter` method, except that it
waits for all promises to become fulfilled before running the `filterFn` on
each item in given to `promises`. `RSVP.filter` returns a promise that will
become fulfilled with the result of running `filterFn` on the values the
promises become fulfilled with.
For example:
```javascript
let promise1 = RSVP.resolve(1);
let promise2 = RSVP.resolve(2);
let promise3 = RSVP.resolve(3);
let promises = [promise1, promise2, promise3];
let filterFn = function(item){
return item > 1;
};
RSVP.filter(promises, filterFn).then(function(result){
// result is [ 2, 3 ]
});
```
If any of the `promises` given to `RSVP.filter` are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
```javascript
let promise1 = RSVP.resolve(1);
let promise2 = RSVP.reject(new Error('2'));
let promise3 = RSVP.reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let filterFn = function(item){
return item > 1;
};
RSVP.filter(promises, filterFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
```
`RSVP.filter` will also wait for any promises returned from `filterFn`.
For instance, you may want to fetch a list of users then return a subset
of those users based on some asynchronous operation:
```javascript
let alice = { name: 'alice' };
let bob = { name: 'bob' };
let users = [ alice, bob ];
let promises = users.map(function(user){
return RSVP.resolve(user);
});
let filterFn = function(user){
// Here, Alice has permissions to create a blog post, but Bob does not.
return getPrivilegesForUser(user).then(function(privs){
return privs.can_create_blog_post === true;
});
};
RSVP.filter(promises, filterFn).then(function(users){
// true, because the server told us only Alice can create a blog post.
users.length === 1;
// false, because Alice is the only user present in `users`
users[0] === bob;
});
```
@method filter
@static
@for RSVP
@param {Array} promises
@param {Function} filterFn - function to be called on each resolved value to
filter the final results.
@param {String} label optional string describing the promise. Useful for
tooling.
@return {Promise}
*/
function resolveAll(promises, label) {
return Promise.all(promises, label);
}
function resolveSingle(promise, label) {
return Promise.resolve(promise, label).then(function (promises) {
return resolveAll(promises, label);
});
}
function filter(promises, filterFn, label) {
if (!isArray(promises) && !(isObject(promises) && promises.then !== undefined)) {
return Promise.reject(new TypeError("RSVP.filter must be called with an array or promise"), label);
}
if (!isFunction(filterFn)) {
return Promise.reject(new TypeError("RSVP.filter expects function as a second argument"), label);
}
var promise = isArray(promises) ? resolveAll(promises, label) : resolveSingle(promises, label);
return promise.then(function (values) {
var length = values.length;
var filtered = new Array(length);
for (var i = 0; i < length; i++) {
filtered[i] = filterFn(values[i]);
}
return resolveAll(filtered, label).then(function (filtered) {
var results = new Array(length);
var newLength = 0;
for (var _i = 0; _i < length; _i++) {
if (filtered[_i]) {
results[newLength] = values[_i];
newLength++;
}
}
results.length = newLength;
return results;
});
});
}
var len = 0;
var vertxNext = void 0;
function asap(callback, arg) {
queue$1[len] = callback;
queue$1[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush$1();
}
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
var nextTick = process.nextTick;
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// setImmediate should be used instead instead
var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
nextTick = setImmediate;
}
return function () {
return nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
return node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function () {
return setTimeout(flush, 1);
};
}
var queue$1 = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue$1[i];
var arg = queue$1[i + 1];
callback(arg);
queue$1[i] = undefined;
queue$1[i + 1] = undefined;
}
len = 0;
}
function attemptVertex() {
try {
var r = require;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush$1 = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush$1 = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush$1 = useMutationObserver();
} else if (isWorker) {
scheduleFlush$1 = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush$1 = attemptVertex();
} else {
scheduleFlush$1 = useSetTimeout();
}
var platform = void 0;
/* global self */
if (typeof self === 'object') {
platform = self;
/* global global */
} else if (typeof global === 'object') {
platform = global;
} else {
throw new Error('no global: `self` or `global` found');
}
var _asap$cast$Promise$Ev;
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// defaults
config.async = asap;
config.after = function (cb) {
return setTimeout(cb, 0);
};
var cast = resolve$2;
var async = function (callback, arg) {
return config.async(callback, arg);
};
function on() {
config['on'].apply(config, arguments);
}
function off() {
config['off'].apply(config, arguments);
}
// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
var callbacks = window['__PROMISE_INSTRUMENTATION__'];
configure('instrument', true);
for (var eventName in callbacks) {
if (callbacks.hasOwnProperty(eventName)) {
on(eventName, callbacks[eventName]);
}
}
}
// the default export here is for backwards compat:
// https://github.com/tildeio/rsvp.js/issues/434
var rsvp = (_asap$cast$Promise$Ev = {
asap: asap,
cast: cast,
Promise: Promise,
EventTarget: EventTarget,
all: all$1,
allSettled: allSettled,
race: race$1,
hash: hash,
hashSettled: hashSettled,
rethrow: rethrow,
defer: defer,
denodeify: denodeify,
configure: configure,
on: on,
off: off,
resolve: resolve$2,
reject: reject$2,
map: map
}, _defineProperty(_asap$cast$Promise$Ev, 'async', async), _defineProperty(_asap$cast$Promise$Ev, 'filter', filter), _asap$cast$Promise$Ev);
exports['default'] = rsvp;
exports.asap = asap;
exports.cast = cast;
exports.Promise = Promise;
exports.EventTarget = EventTarget;
exports.all = all$1;
exports.allSettled = allSettled;
exports.race = race$1;
exports.hash = hash;
exports.hashSettled = hashSettled;
exports.rethrow = rethrow;
exports.defer = defer;
exports.denodeify = denodeify;
exports.configure = configure;
exports.on = on;
exports.off = off;
exports.resolve = resolve$2;
exports.reject = reject$2;
exports.map = map;
exports.async = async;
exports.filter = filter;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//
var EPUBJS = EPUBJS || {};
EPUBJS.core = {};
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_NODE = 9;
//-- Get a element for an id
EPUBJS.core.getEl = function(elem) {
return document.getElementById(elem);
};
//-- Get all elements for a class
EPUBJS.core.getEls = function(classes) {
return document.getElementsByClassName(classes);
};
EPUBJS.core.request = function(url, type, withCredentials) {
var supportsURL = window.URL;
var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer";
var deferred = new RSVP.defer();
var xhr = new XMLHttpRequest();
var uri;
//-- Check from PDF.js:
// https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js
var xhrPrototype = XMLHttpRequest.prototype;
var handler = function() {
var r;
if (this.readyState != this.DONE) return;
if ((this.status === 200 || this.status === 0) && this.response) { // Android & Firefox reporting 0 for local & blob urls
if (type == 'xml'){
// If this.responseXML wasn't set, try to parse using a DOMParser from text
if(!this.responseXML) {
r = new DOMParser().parseFromString(this.response, "application/xml");
} else {
r = this.responseXML;
}
} else if (type == 'xhtml') {
if (!this.responseXML){
r = new DOMParser().parseFromString(this.response, "application/xhtml+xml");
} else {
r = this.responseXML;
}
} else if (type == 'html') {
if (!this.responseXML){
r = new DOMParser().parseFromString(this.response, "text/html");
} else {
r = this.responseXML;
}
} else if (type == 'json') {
r = JSON.parse(this.response);
} else if (type == 'blob') {
if (supportsURL) {
r = this.response;
} else {
//-- Safari doesn't support responseType blob, so create a blob from arraybuffer
r = new Blob([this.response]);
}
} else {
r = this.response;
}
deferred.resolve(r);
} else {
deferred.reject({
message : this.response,
stack : new Error().stack
});
}
};
if (!('overrideMimeType' in xhrPrototype)) {
// IE10 might have response, but not overrideMimeType
Object.defineProperty(xhrPrototype, 'overrideMimeType', {
value: function xmlHttpRequestOverrideMimeType(mimeType) {}
});
}
xhr.onreadystatechange = handler;
xhr.open("GET", url, true);
if(withCredentials) {
xhr.withCredentials = true;
}
// If type isn't set, determine it from the file extension
if(!type) {
uri = EPUBJS.core.uri(url);
type = uri.extension;
type = {
'htm': 'html'
}[type] || type;
}
if(type == 'blob'){
xhr.responseType = BLOB_RESPONSE;
}
if(type == "json") {
xhr.setRequestHeader("Accept", "application/json");
}
if(type == 'xml') {
xhr.responseType = "document";
xhr.overrideMimeType('text/xml'); // for OPF parsing
}
if(type == 'xhtml') {
xhr.responseType = "document";
}
if(type == 'html') {
xhr.responseType = "document";
}
if(type == "binary") {
xhr.responseType = "arraybuffer";
}
xhr.send();
return deferred.promise;
};
EPUBJS.core.toArray = function(obj) {
var arr = [];
for (var member in obj) {
var newitm;
if ( obj.hasOwnProperty(member) ) {
newitm = obj[member];
newitm.ident = member;
arr.push(newitm);
}
}
return arr;
};
//-- Parse the different parts of a url, returning a object
EPUBJS.core.uri = function(url){
var uri = {
protocol : '',
host : '',
path : '',
origin : '',
directory : '',
base : '',
filename : '',
extension : '',
fragment : '',
href : url
},
blob = url.indexOf('blob:'),
doubleSlash = url.indexOf('://'),
search = url.indexOf('?'),
fragment = url.indexOf("#"),
withoutProtocol,
dot,
firstSlash;
if(blob === 0) {
uri.protocol = "blob";
uri.base = url.indexOf(0, fragment);
return uri;
}
if(fragment != -1) {
uri.fragment = url.slice(fragment + 1);
url = url.slice(0, fragment);
}
if(search != -1) {
uri.search = url.slice(search + 1);
url = url.slice(0, search);
href = uri.href;
}
if(doubleSlash != -1) {
uri.protocol = url.slice(0, doubleSlash);
withoutProtocol = url.slice(doubleSlash+3);
firstSlash = withoutProtocol.indexOf('/');
if(firstSlash === -1) {
uri.host = uri.path;
uri.path = "";
} else {
uri.host = withoutProtocol.slice(0, firstSlash);
uri.path = withoutProtocol.slice(firstSlash);
}
uri.origin = uri.protocol + "://" + uri.host;
uri.directory = EPUBJS.core.folder(uri.path);
uri.base = uri.origin + uri.directory;
// return origin;
} else {
uri.path = url;
uri.directory = EPUBJS.core.folder(url);
uri.base = uri.directory;
}
//-- Filename
uri.filename = url.replace(uri.base, '');
dot = uri.filename.lastIndexOf('.');
if(dot != -1) {
uri.extension = uri.filename.slice(dot+1);
}
return uri;
};
//-- Parse out the folder, will return everything before the last slash
EPUBJS.core.folder = function(url){
var lastSlash = url.lastIndexOf('/');
if(lastSlash == -1) var folder = '';
folder = url.slice(0, lastSlash + 1);
return folder;
};
//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128
EPUBJS.core.dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,',
parts, contentType, raw, rawLength, uInt8Array;
if (dataURL.indexOf(BASE64_MARKER) == -1) {
parts = dataURL.split(',');
contentType = parts[0].split(':')[1];
raw = parts[1];
return new Blob([raw], {type: contentType});
}
parts = dataURL.split(BASE64_MARKER);
contentType = parts[0].split(':')[1];
raw = window.atob(parts[1]);
rawLength = raw.length;
uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
};
//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously
EPUBJS.core.addScript = function(src, callback, target) {
var s, r;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.async = false;
s.src = src;
s.onload = s.onreadystatechange = function() {
if ( !r && (!this.readyState || this.readyState == 'complete') ) {
r = true;
if(callback) callback();
}
};
target = target || document.body;
target.appendChild(s);
};
EPUBJS.core.addScripts = function(srcArr, callback, target) {
var total = srcArr.length,
curr = 0,
cb = function(){
curr++;
if(total == curr){
if(callback) callback();
}else{
EPUBJS.core.addScript(srcArr[curr], cb, target);
}
};
EPUBJS.core.addScript(srcArr[curr], cb, target);
};
EPUBJS.core.addCss = function(src, callback, target) {
var s, r;
r = false;
s = document.createElement('link');
s.type = 'text/css';
s.rel = "stylesheet";
s.href = src;
s.onload = s.onreadystatechange = function() {
if ( !r && (!this.readyState || this.readyState == 'complete') ) {
r = true;
if(callback) callback();
}
};
target = target || document.body;
target.appendChild(s);
};
EPUBJS.core.prefixed = function(unprefixed) {
var vendors = ["Webkit", "Moz", "O", "ms" ],
prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'],
upper = unprefixed[0].toUpperCase() + unprefixed.slice(1),
length = vendors.length;
if (typeof(document.documentElement.style[unprefixed]) != 'undefined') {
return unprefixed;
}
for ( var i=0; i < length; i++ ) {
if (typeof(document.documentElement.style[vendors[i] + upper]) != 'undefined') {
return vendors[i] + upper;
}
}
return unprefixed;
};
EPUBJS.core.resolveUrl = function(base, path) {
var url,
segments = [],
uri = EPUBJS.core.uri(path),
folders = base.split("/"),
paths;
if(uri.host) {
return path;
}
folders.pop();
paths = path.split("/");
paths.forEach(function(p){
if(p === ".."){
folders.pop();
}else{
segments.push(p);
}
});
url = folders.concat(segments);
return url.join("/");
};
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
EPUBJS.core.uuid = function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
};
// Fast quicksort insert for sorted array -- based on:
// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers
EPUBJS.core.insert = function(item, array, compareFunction) {
var location = EPUBJS.core.locationOf(item, array, compareFunction);
array.splice(location, 0, item);
return location;
};
EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) {
var start = _start || 0;
var end = _end || array.length;
var pivot = parseInt(start + (end - start) / 2);
var compared;
if(!compareFunction){
compareFunction = function(a, b) {
if(a > b) return 1;
if(a < b) return -1;
if(a = b) return 0;
};
}
if(end-start <= 0) {
return pivot;
}
compared = compareFunction(array[pivot], item);
if(end-start === 1) {
return compared > 0 ? pivot : pivot + 1;
}
if(compared === 0) {
return pivot;
}
if(compared === -1) {
return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end);
} else{
return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot);
}
};
EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) {
var start = _start || 0;
var end = _end || array.length;
var pivot = parseInt(start + (end - start) / 2);
var compared;
if(!compareFunction){
compareFunction = function(a, b) {
if(a > b) return 1;
if(a < b) return -1;
if(a = b) return 0;
};
}
if(end-start <= 0) {
return -1; // Not found
}
compared = compareFunction(array[pivot], item);
if(end-start === 1) {
return compared === 0 ? pivot : -1;
}
if(compared === 0) {
return pivot; // Found
}
if(compared === -1) {
return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end);
} else{
return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot);
}
};
EPUBJS.core.queue = function(_scope){
var _q = [];
var scope = _scope;
// Add an item to the queue
var enqueue = function(funcName, args, context) {
_q.push({
"funcName" : funcName,
"args" : args,
"context" : context
});
return _q;
};
// Run one item
var dequeue = function(){
var inwait;
if(_q.length) {
inwait = _q.shift();
// Defer to any current tasks
// setTimeout(function(){
scope[inwait.funcName].apply(inwait.context || scope, inwait.args);
// }, 0);
}
};
// Run All
var flush = function(){
while(_q.length) {
dequeue();
}
};
// Clear all items in wait
var clear = function(){
_q = [];
};
var length = function(){
return _q.length;
};
return {
"enqueue" : enqueue,
"dequeue" : dequeue,
"flush" : flush,
"clear" : clear,
"length" : length
};
};
// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js
/**
* Gets an XPath for an element which describes its hierarchical location.
*/
EPUBJS.core.getElementXPath = function(element) {
if (element && element.id) {
return '//*[@id="' + element.id + '"]';
} else {
return EPUBJS.core.getElementTreeXPath(element);
}
};
EPUBJS.core.getElementTreeXPath = function(element) {
var paths = [];
var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml");
var index, nodeName, tagName, pathIndex;
if(element.nodeType === Node.TEXT_NODE){
// index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1;
index = EPUBJS.core.indexOfTextNode(element) + 1;
paths.push("text()["+index+"]");
element = element.parentNode;
}
// Use nodeName (instead of localName) so namespace prefix is included (if any).
for (; element && element.nodeType == 1; element = element.parentNode)
{
index = 0;
for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling)
{
// Ignore document type declaration.
if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) {
continue;
}
if (sibling.nodeName == element.nodeName) {
++index;
}
}
nodeName = element.nodeName.toLowerCase();
tagName = (isXhtml ? "xhtml:" + nodeName : nodeName);
pathIndex = (index ? "[" + (index+1) + "]" : "");
paths.splice(0, 0, tagName + pathIndex);
}
return paths.length ? "./" + paths.join("/") : null;
};
EPUBJS.core.nsResolver = function(prefix) {
var ns = {
'xhtml' : 'http://www.w3.org/1999/xhtml',
'epub': 'http://www.idpf.org/2007/ops'
};
return ns[prefix] || null;
};
//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496
EPUBJS.core.cleanStringForXpath = function(str) {
var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){
if (part === "'") {
return '\"\'\"'; // output "'"
}
if (part === '"') {
return "\'\"\'"; // output '"'
}
return "\'" + part + "\'";
});
return "concat(\'\'," + parts.join(",") + ")";
};
EPUBJS.core.indexOfTextNode = function(textNode){
var parent = textNode.parentNode;
var children = parent.childNodes;
var sib;
var index = -1;
for (var i = 0; i < children.length; i++) {
sib = children[i];
if(sib.nodeType === Node.TEXT_NODE){
index++;
}
if(sib == textNode) break;
}
return index;
};
// Underscore
EPUBJS.core.defaults = function(obj) {
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
return obj;
};
EPUBJS.core.extend = function(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
if(!source) return;
Object.getOwnPropertyNames(source).forEach(function(propName) {
Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName));
});
});
return target;
};
EPUBJS.core.clone = function(obj) {
return EPUBJS.core.isArray(obj) ? obj.slice() : EPUBJS.core.extend({}, obj);
};
EPUBJS.core.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
EPUBJS.core.isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
EPUBJS.core.isString = function(str) {
return (typeof str === 'string' || str instanceof String);
};
EPUBJS.core.isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
// Lodash
EPUBJS.core.values = function(object) {
var index = -1;
var props, length, result;
if(!object) return [];
props = Object.keys(object);
length = props.length;
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
};
EPUBJS.core.indexOfNode = function(node, typeId) {
var parent = node.parentNode;
var children = parent.childNodes;
var sib;
var index = -1;
for (var i = 0; i < children.length; i++) {
sib = children[i];
if (sib.nodeType === typeId) {
index++;
}
if (sib == node) break;
}
return index;
}
EPUBJS.core.indexOfTextNode = function(textNode) {
return EPUBJS.core.indexOfNode(textNode, TEXT_NODE);
}
EPUBJS.core.indexOfElementNode = function(elementNode) {
return EPUBJS.core.indexOfNode(elementNode, ELEMENT_NODE);
}
var EPUBJS = EPUBJS || {};
EPUBJS.reader = {};
EPUBJS.reader.plugins = {}; //-- Attach extra Controllers as plugins (like search?)
(function(root, $) {
var previousReader = root.ePubReader || {};
var ePubReader = root.ePubReader = function(path, options) {
return new EPUBJS.Reader(path, options);
};
//exports to multiple environments
if (typeof define === 'function' && define.amd) {
//AMD
define(function(){ return Reader; });
} else if (typeof module != "undefined" && module.exports) {
//Node
module.exports = ePubReader;
}
})(window, jQuery);
EPUBJS.Reader = function(bookPath, _options) {
var reader = this;
var book;
var plugin;
var $viewer = $("#viewer");
var search = window.location.search;
var parameters;
this.settings = EPUBJS.core.defaults(_options || {}, {
bookPath : bookPath,
restore : false,
reload : false,
bookmarks : undefined,
annotations : undefined,
contained : undefined,
bookKey : undefined,
styles : undefined,
sidebarReflow: false,
generatePagination: false,
history: true
});
// Overide options with search parameters
if(search) {
parameters = search.slice(1).split("&");
parameters.forEach(function(p){
var split = p.split("=");
var name = split[0];
var value = split[1] || '';
reader.settings[name] = decodeURIComponent(value);
});
}
this.setBookKey(this.settings.bookPath); //-- This could be username + path or any unique string
if(this.settings.restore && this.isSaved()) {
this.applySavedSettings();
}
this.settings.styles = this.settings.styles || {
fontSize : "100%"
};
this.book = book = new ePub(this.settings.bookPath, this.settings);
this.offline = false;
this.sidebarOpen = false;
if(!this.settings.bookmarks) {
this.settings.bookmarks = [];
}
if(!this.settings.annotations) {
this.settings.annotations = [];
}
if(this.settings.generatePagination) {
book.generatePagination($viewer.width(), $viewer.height());
}
this.rendition = book.renderTo("viewer", {
ignoreClass: "annotator-hl",
width: "100%",
height: "100%"
});
if(this.settings.previousLocationCfi) {
this.displayed = this.rendition.display(this.settings.previousLocationCfi);
} else {
this.displayed = this.rendition.display();
}
book.ready.then(function () {
reader.ReaderController = EPUBJS.reader.ReaderController.call(reader, book);
reader.SettingsController = EPUBJS.reader.SettingsController.call(reader, book);
reader.ControlsController = EPUBJS.reader.ControlsController.call(reader, book);
reader.SidebarController = EPUBJS.reader.SidebarController.call(reader, book);
reader.BookmarksController = EPUBJS.reader.BookmarksController.call(reader, book);
reader.NotesController = EPUBJS.reader.NotesController.call(reader, book);
window.addEventListener("hashchange", this.hashChanged.bind(this), false);
document.addEventListener('keydown', this.adjustFontSize.bind(this), false);
this.rendition.on("keydown", this.adjustFontSize.bind(this));
this.rendition.on("keydown", reader.ReaderController.arrowKeys.bind(this));
this.rendition.on("selected", this.selectedRange.bind(this));
}.bind(this)).then(function() {
reader.ReaderController.hideLoader();
}.bind(this));
// Call Plugins
for(plugin in EPUBJS.reader.plugins) {
if(EPUBJS.reader.plugins.hasOwnProperty(plugin)) {
reader[plugin] = EPUBJS.reader.plugins[plugin].call(reader, book);
}
}
book.loaded.metadata.then(function(meta) {
reader.MetaController = EPUBJS.reader.MetaController.call(reader, meta);
});
book.loaded.navigation.then(function(navigation) {
reader.TocController = EPUBJS.reader.TocController.call(reader, navigation);
});
window.addEventListener("beforeunload", this.unload.bind(this), false);
return this;
};
EPUBJS.Reader.prototype.adjustFontSize = function(e) {
var fontSize;
var interval = 2;
var PLUS = 187;
var MINUS = 189;
var ZERO = 48;
var MOD = (e.ctrlKey || e.metaKey );
if(!this.settings.styles) return;
if(!this.settings.styles.fontSize) {
this.settings.styles.fontSize = "100%";
}
fontSize = parseInt(this.settings.styles.fontSize.slice(0, -1));
if(MOD && e.keyCode == PLUS) {
e.preventDefault();
this.book.setStyle("fontSize", (fontSize + interval) + "%");
}
if(MOD && e.keyCode == MINUS){
e.preventDefault();
this.book.setStyle("fontSize", (fontSize - interval) + "%");
}
if(MOD && e.keyCode == ZERO){
e.preventDefault();
this.book.setStyle("fontSize", "100%");
}
};
EPUBJS.Reader.prototype.addBookmark = function(cfi) {
var present = this.isBookmarked(cfi);
if(present > -1 ) return;
this.settings.bookmarks.push(cfi);
this.trigger("reader:bookmarked", cfi);
};
EPUBJS.Reader.prototype.removeBookmark = function(cfi) {
var bookmark = this.isBookmarked(cfi);
if( bookmark === -1 ) return;
this.settings.bookmarks.splice(bookmark, 1);
this.trigger("reader:unbookmarked", bookmark);
};
EPUBJS.Reader.prototype.isBookmarked = function(cfi) {
var bookmarks = this.settings.bookmarks;
return bookmarks.indexOf(cfi);
};
/*
EPUBJS.Reader.prototype.searchBookmarked = function(cfi) {
var bookmarks = this.settings.bookmarks,
len = bookmarks.length,
i;
for(i = 0; i < len; i++) {
if (bookmarks[i]['cfi'] === cfi) return i;
}
return -1;
};
*/
EPUBJS.Reader.prototype.clearBookmarks = function() {
this.settings.bookmarks = [];
};
//-- Notes
EPUBJS.Reader.prototype.addNote = function(note) {
this.settings.annotations.push(note);
};
EPUBJS.Reader.prototype.removeNote = function(note) {
var index = this.settings.annotations.indexOf(note);
if( index === -1 ) return;
delete this.settings.annotations[index];
};
EPUBJS.Reader.prototype.clearNotes = function() {
this.settings.annotations = [];
};
//-- Settings
EPUBJS.Reader.prototype.setBookKey = function(identifier){
if(!this.settings.bookKey) {
this.settings.bookKey = "epubjsreader:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier;
}
return this.settings.bookKey;
};
//-- Checks if the book setting can be retrieved from localStorage
EPUBJS.Reader.prototype.isSaved = function(bookPath) {
var storedSettings;
if(!localStorage) {
return false;
}
storedSettings = localStorage.getItem(this.settings.bookKey);
if(storedSettings === null) {
return false;
} else {
return true;
}
};
EPUBJS.Reader.prototype.removeSavedSettings = function() {
if(!localStorage) {
return false;
}
localStorage.removeItem(this.settings.bookKey);
};
EPUBJS.Reader.prototype.applySavedSettings = function() {
var stored;
if(!localStorage) {
return false;
}
try {
stored = JSON.parse(localStorage.getItem(this.settings.bookKey));
} catch (e) { // parsing error of localStorage
return false;
}
if(stored) {
// Merge styles
if(stored.styles) {
this.settings.styles = EPUBJS.core.defaults(this.settings.styles || {}, stored.styles);
}
// Merge the rest
this.settings = EPUBJS.core.defaults(this.settings, stored);
return true;
} else {
return false;
}
};
EPUBJS.Reader.prototype.saveSettings = function(){
if(this.book) {
this.settings.previousLocationCfi = this.rendition.currentLocation().start.cfi;
}
if(!localStorage) {
return false;
}
localStorage.setItem(this.settings.bookKey, JSON.stringify(this.settings));
};
EPUBJS.Reader.prototype.unload = function(){
if(this.settings.restore && localStorage) {
this.saveSettings();
}
};
EPUBJS.Reader.prototype.hashChanged = function(){
var hash = window.location.hash.slice(1);
this.rendition.display(hash);
};
EPUBJS.Reader.prototype.selectedRange = function(cfiRange){
var cfiFragment = "#"+cfiRange;
// Update the History Location
if(this.settings.history &&
window.location.hash != cfiFragment) {
// Add CFI fragment to the history
history.pushState({}, '', cfiFragment);
this.currentLocationCfi = cfiRange;
}
};
//-- Enable binding events to reader
RSVP.EventTarget.mixin(EPUBJS.Reader.prototype);
EPUBJS.reader.BookmarksController = function() {
var reader = this;
var book = this.book;
var rendition = this.rendition;
var $bookmarks = $("#bookmarksView"),
$list = $bookmarks.find("#bookmarks");
var docfrag = document.createDocumentFragment();
var show = function() {
$bookmarks.show();
};
var hide = function() {
$bookmarks.hide();
};
var counter = 0;
var createBookmarkItem = function(cfi) {
var listitem = document.createElement("li"),
link = document.createElement("a");
listitem.id = "bookmark-"+counter;
listitem.classList.add('list_item');
var spineItem = book.spine.get(cfi);
var tocItem;
if (spineItem.index in book.navigation.toc) {
tocItem = book.navigation.toc[spineItem.index];
link.textContent = tocItem.label;
} else {
link.textContent = cfi;
}
link.href = cfi;
link.classList.add('bookmark_link');
link.addEventListener("click", function(event){
var cfi = this.getAttribute('href');
rendition.display(cfi);
event.preventDefault();
}, false);
listitem.appendChild(link);
counter++;
return listitem;
};
this.settings.bookmarks.forEach(function(cfi) {
var bookmark = createBookmarkItem(cfi);
docfrag.appendChild(bookmark);
});
$list.append(docfrag);
this.on("reader:bookmarked", function(cfi) {
var item = createBookmarkItem(cfi);
$list.append(item);
});
this.on("reader:unbookmarked", function(index) {
var $item = $("#bookmark-"+index);
$item.remove();
});
return {
"show" : show,
"hide" : hide
};
};
EPUBJS.reader.ControlsController = function(book) {
var reader = this;
var rendition = this.rendition;
var $store = $("#store"),
$fullscreen = $("#fullscreen"),
$fullscreenicon = $("#fullscreenicon"),
$cancelfullscreenicon = $("#cancelfullscreenicon"),
$slider = $("#slider"),
$main = $("#main"),
$sidebar = $("#sidebar"),
$settings = $("#setting"),
$bookmark = $("#bookmark");
/*
var goOnline = function() {
reader.offline = false;
// $store.attr("src", $icon.data("save"));
};
var goOffline = function() {
reader.offline = true;
// $store.attr("src", $icon.data("saved"));
};
var fullscreen = false;
book.on("book:online", goOnline);
book.on("book:offline", goOffline);
*/
$slider.on("click", function () {
if(reader.sidebarOpen) {
reader.SidebarController.hide();
$slider.addClass("icon-menu");
$slider.removeClass("icon-right");
} else {
reader.SidebarController.show();
$slider.addClass("icon-right");
$slider.removeClass("icon-menu");
}
});
if(typeof screenfull !== 'undefined') {
$fullscreen.on("click", function() {
screenfull.toggle($('#container')[0]);
});
if(screenfull.raw) {
document.addEventListener(screenfull.raw.fullscreenchange, function() {
fullscreen = screenfull.isFullscreen;
if(fullscreen) {
$fullscreen
.addClass("icon-resize-small")
.removeClass("icon-resize-full");
} else {
$fullscreen
.addClass("icon-resize-full")
.removeClass("icon-resize-small");
}
});
}
}
$settings.on("click", function() {
reader.SettingsController.show();
});
$bookmark.on("click", function() {
var cfi = reader.rendition.currentLocation().start.cfi;
var bookmarked = reader.isBookmarked(cfi);
if(bookmarked === -1) { //-- Add bookmark
reader.addBookmark(cfi);
$bookmark
.addClass("icon-bookmark")
.removeClass("icon-bookmark-empty");
} else { //-- Remove Bookmark
reader.removeBookmark(cfi);
$bookmark
.removeClass("icon-bookmark")
.addClass("icon-bookmark-empty");
}
});
rendition.on('relocated', function(location){
var cfi = location.start.cfi;
var cfiFragment = "#" + cfi;
//-- Check if bookmarked
var bookmarked = reader.isBookmarked(cfi);
if(bookmarked === -1) { //-- Not bookmarked
$bookmark
.removeClass("icon-bookmark")
.addClass("icon-bookmark-empty");
} else { //-- Bookmarked
$bookmark
.addClass("icon-bookmark")
.removeClass("icon-bookmark-empty");
}
reader.currentLocationCfi = cfi;
// Update the History Location
if(reader.settings.history &&
window.location.hash != cfiFragment) {
// Add CFI fragment to the history
history.pushState({}, '', cfiFragment);
}
});
return {
};
};
EPUBJS.reader.MetaController = function(meta) {
var title = meta.title,
author = meta.creator;
var $title = $("#book-title"),
$author = $("#chapter-title"),
$dash = $("#title-seperator");
document.title = title+" – "+author;
$title.html(title);
$author.html(author);
$dash.show();
};
EPUBJS.reader.NotesController = function() {
var book = this.book;
var rendition = this.rendition;
var reader = this;
var $notesView = $("#notesView");
var $notes = $("#notes");
var $text = $("#note-text");
var $anchor = $("#note-anchor");
var annotations = reader.settings.annotations;
var renderer = book.renderer;
var popups = [];
var epubcfi = new ePub.CFI();
var show = function() {
$notesView.show();
};
var hide = function() {
$notesView.hide();
}
var insertAtPoint = function(e) {
var range;
var textNode;
var offset;
var doc = book.renderer.doc;
var cfi;
var annotation;
// standard
if (doc.caretPositionFromPoint) {
range = doc.caretPositionFromPoint(e.clientX, e.clientY);
textNode = range.offsetNode;
offset = range.offset;
// WebKit
} else if (doc.caretRangeFromPoint) {
range = doc.caretRangeFromPoint(e.clientX, e.clientY);
textNode = range.startContainer;
offset = range.startOffset;
}
if (textNode.nodeType !== 3) {
for (var i=0; i < textNode.childNodes.length; i++) {
if (textNode.childNodes[i].nodeType == 3) {
textNode = textNode.childNodes[i];
break;
}
}
}
// Find the end of the sentance
offset = textNode.textContent.indexOf(".", offset);
if(offset === -1){
offset = textNode.length; // Last item
} else {
offset += 1; // After the period
}
cfi = epubcfi.generateCfiFromTextNode(textNode, offset, book.renderer.currentChapter.cfiBase);
annotation = {
annotatedAt: new Date(),
anchor: cfi,
body: $text.val()
}
// add to list
reader.addNote(annotation);
// attach
addAnnotation(annotation);
placeMarker(annotation);
// clear
$text.val('');
$anchor.text("Attach");
$text.prop("disabled", false);
rendition.off("click", insertAtPoint);
};
var addAnnotation = function(annotation){
var note = document.createElement("li");
var link = document.createElement("a");
note.innerHTML = annotation.body;
// note.setAttribute("ref", annotation.anchor);
link.innerHTML = " context »";
link.href = "#"+annotation.anchor;
link.onclick = function(){
rendition.display(annotation.anchor);
return false;
};
note.appendChild(link);
$notes.append(note);
};
var placeMarker = function(annotation){
var doc = book.renderer.doc;
var marker = document.createElement("span");
var mark = document.createElement("a");
marker.classList.add("footnotesuperscript", "reader_generated");
marker.style.verticalAlign = "super";
marker.style.fontSize = ".75em";
// marker.style.position = "relative";
marker.style.lineHeight = "1em";
// mark.style.display = "inline-block";
mark.style.padding = "2px";
mark.style.backgroundColor = "#fffa96";
mark.style.borderRadius = "5px";
mark.style.cursor = "pointer";
marker.id = "note-"+EPUBJS.core.uuid();
mark.innerHTML = annotations.indexOf(annotation) + 1 + "[Reader]";
marker.appendChild(mark);
epubcfi.addMarker(annotation.anchor, doc, marker);
markerEvents(marker, annotation.body);
}
var markerEvents = function(item, txt){
var id = item.id;
var showPop = function(){
var poppos,
iheight = renderer.height,
iwidth = renderer.width,
tip,
pop,
maxHeight = 225,
itemRect,
left,
top,
pos;
//-- create a popup with endnote inside of it
if(!popups[id]) {
popups[id] = document.createElement("div");
popups[id].setAttribute("class", "popup");
pop_content = document.createElement("div");
popups[id].appendChild(pop_content);
pop_content.innerHTML = txt;
pop_content.setAttribute("class", "pop_content");
renderer.render.document.body.appendChild(popups[id]);
//-- TODO: will these leak memory? - Fred
popups[id].addEventListener("mouseover", onPop, false);
popups[id].addEventListener("mouseout", offPop, false);
//-- Add hide on page change
rendition.on("locationChanged", hidePop, this);
rendition.on("locationChanged", offPop, this);
// chapter.book.on("renderer:chapterDestroy", hidePop, this);
}
pop = popups[id];
//-- get location of item
itemRect = item.getBoundingClientRect();
left = itemRect.left;
top = itemRect.top;
//-- show the popup
pop.classList.add("show");
//-- locations of popup
popRect = pop.getBoundingClientRect();
//-- position the popup
pop.style.left = left - popRect.width / 2 + "px";
pop.style.top = top + "px";
//-- Adjust max height
if(maxHeight > iheight / 2.5) {
maxHeight = iheight / 2.5;
pop_content.style.maxHeight = maxHeight + "px";
}
//-- switch above / below
if(popRect.height + top >= iheight - 25) {
pop.style.top = top - popRect.height + "px";
pop.classList.add("above");
}else{
pop.classList.remove("above");
}
//-- switch left
if(left - popRect.width <= 0) {
pop.style.left = left + "px";
pop.classList.add("left");
}else{
pop.classList.remove("left");
}
//-- switch right
if(left + popRect.width / 2 >= iwidth) {
//-- TEMP MOVE: 300
pop.style.left = left - 300 + "px";
popRect = pop.getBoundingClientRect();
pop.style.left = left - popRect.width + "px";
//-- switch above / below again
if(popRect.height + top >= iheight - 25) {
pop.style.top = top - popRect.height + "px";
pop.classList.add("above");
}else{
pop.classList.remove("above");
}
pop.classList.add("right");
}else{
pop.classList.remove("right");
}
}
var onPop = function(){
popups[id].classList.add("on");
}
var offPop = function(){
popups[id].classList.remove("on");
}
var hidePop = function(){
setTimeout(function(){
popups[id].classList.remove("show");
}, 100);
}
var openSidebar = function(){
reader.ReaderController.slideOut();
show();
};
item.addEventListener("mouseover", showPop, false);
item.addEventListener("mouseout", hidePop, false);
item.addEventListener("click", openSidebar, false);
}
$anchor.on("click", function(e){
$anchor.text("Cancel");
$text.prop("disabled", "true");
// listen for selection
rendition.on("click", insertAtPoint);
});
annotations.forEach(function(note) {
addAnnotation(note);
});
/*
renderer.registerHook("beforeChapterDisplay", function(callback, renderer){
var chapter = renderer.currentChapter;
annotations.forEach(function(note) {
var cfi = epubcfi.parse(note.anchor);
if(cfi.spinePos === chapter.spinePos) {
try {
placeMarker(note);
} catch(e) {
console.log("anchoring failed", note.anchor);
}
}
});
callback();
}, true);
*/
return {
"show" : show,
"hide" : hide
};
};
EPUBJS.reader.ReaderController = function(book) {
var $main = $("#main"),
$divider = $("#divider"),
$loader = $("#loader"),
$next = $("#next"),
$prev = $("#prev");
var reader = this;
var book = this.book;
var rendition = this.rendition;
var slideIn = function() {
var currentPosition = rendition.currentLocation().start.cfi;
if (reader.settings.sidebarReflow){
$main.removeClass('single');
$main.one("transitionend", function(){
rendition.resize();
});
} else {
$main.removeClass("closed");
}
};
var slideOut = function() {
var location = rendition.currentLocation();
if (!location) {
return;
}
var currentPosition = location.start.cfi;
if (reader.settings.sidebarReflow){
$main.addClass('single');
$main.one("transitionend", function(){
rendition.resize();
});
} else {
$main.addClass("closed");
}
};
var showLoader = function() {
$loader.show();
hideDivider();
};
var hideLoader = function() {
$loader.hide();
//-- If the book is using spreads, show the divider
// if(book.settings.spreads) {
// showDivider();
// }
};
var showDivider = function() {
$divider.addClass("show");
};
var hideDivider = function() {
$divider.removeClass("show");
};
var keylock = false;
var arrowKeys = function(e) {
if(e.keyCode == 37) {
if(book.package.metadata.direction === "rtl") {
rendition.next();
} else {
rendition.prev();
}
$prev.addClass("active");
keylock = true;
setTimeout(function(){
keylock = false;
$prev.removeClass("active");
}, 100);
e.preventDefault();
}
if(e.keyCode == 39) {
if(book.package.metadata.direction === "rtl") {
rendition.prev();
} else {
rendition.next();
}
$next.addClass("active");
keylock = true;
setTimeout(function(){
keylock = false;
$next.removeClass("active");
}, 100);
e.preventDefault();
}
}
document.addEventListener('keydown', arrowKeys, false);
$next.on("click", function(e){
if(book.package.metadata.direction === "rtl") {
rendition.prev();
} else {
rendition.next();
}
e.preventDefault();
});
$prev.on("click", function(e){
if(book.package.metadata.direction === "rtl") {
rendition.next();
} else {
rendition.prev();
}
e.preventDefault();
});
rendition.on("layout", function(props){
if(props.spread === true) {
showDivider();
} else {
hideDivider();
}
});
rendition.on('relocated', function(location){
if (location.atStart) {
$prev.addClass("disabled");
}
if (location.atEnd) {
$next.addClass("disabled");
}
});
return {
"slideOut" : slideOut,
"slideIn" : slideIn,
"showLoader" : showLoader,
"hideLoader" : hideLoader,
"showDivider" : showDivider,
"hideDivider" : hideDivider,
"arrowKeys" : arrowKeys
};
};
EPUBJS.reader.SettingsController = function() {
var book = this.book;
var reader = this;
var $settings = $("#settings-modal"),
$overlay = $(".overlay");
var show = function() {
$settings.addClass("md-show");
};
var hide = function() {
$settings.removeClass("md-show");
};
var $sidebarReflowSetting = $('#sidebarReflow');
$sidebarReflowSetting.on('click', function() {
reader.settings.sidebarReflow = !reader.settings.sidebarReflow;
});
$settings.find(".closer").on("click", function() {
hide();
});
$overlay.on("click", function() {
hide();
});
return {
"show" : show,
"hide" : hide
};
};
EPUBJS.reader.SidebarController = function(book) {
var reader = this;
var $sidebar = $("#sidebar"),
$panels = $("#panels");
var activePanel = "Toc";
var changePanelTo = function(viewName) {
var controllerName = viewName + "Controller";
if(activePanel == viewName || typeof reader[controllerName] === 'undefined' ) return;
reader[activePanel+ "Controller"].hide();
reader[controllerName].show();
activePanel = viewName;
$panels.find('.active').removeClass("active");
$panels.find("#show-" + viewName ).addClass("active");
};
var getActivePanel = function() {
return activePanel;
};
var show = function() {
reader.sidebarOpen = true;
reader.ReaderController.slideOut();
$sidebar.addClass("open");
}
var hide = function() {
reader.sidebarOpen = false;
reader.ReaderController.slideIn();
$sidebar.removeClass("open");
}
$panels.find(".show_view").on("click", function(event) {
var view = $(this).data("view");
changePanelTo(view);
event.preventDefault();
});
return {
'show' : show,
'hide' : hide,
'getActivePanel' : getActivePanel,
'changePanelTo' : changePanelTo
};
};
EPUBJS.reader.TocController = function(toc) {
var book = this.book;
var rendition = this.rendition;
var $list = $("#tocView"),
docfrag = document.createDocumentFragment();
var currentChapter = false;
var generateTocItems = function(toc, level) {
var container = document.createElement("ul");
if(!level) level = 1;
toc.forEach(function(chapter) {
var listitem = document.createElement("li"),
link = document.createElement("a");
toggle = document.createElement("a");
var subitems;
listitem.id = "toc-"+chapter.id;
listitem.classList.add('list_item');
link.textContent = chapter.label;
link.href = chapter.href;
link.classList.add('toc_link');
listitem.appendChild(link);
if(chapter.subitems && chapter.subitems.length > 0) {
level++;
subitems = generateTocItems(chapter.subitems, level);
toggle.classList.add('toc_toggle');
listitem.insertBefore(toggle, link);
listitem.appendChild(subitems);
}
container.appendChild(listitem);
});
return container;
};
var onShow = function() {
$list.show();
};
var onHide = function() {
$list.hide();
};
var chapterChange = function(e) {
var id = e.id,
$item = $list.find("#toc-"+id),
$current = $list.find(".currentChapter"),
$open = $list.find('.openChapter');
if($item.length){
if($item != $current && $item.has(currentChapter).length > 0) {
$current.removeClass("currentChapter");
}
$item.addClass("currentChapter");
// $open.removeClass("openChapter");
$item.parents('li').addClass("openChapter");
}
};
rendition.on('renderered', chapterChange);
var tocitems = generateTocItems(toc);
docfrag.appendChild(tocitems);
$list.append(docfrag);
$list.find(".toc_link").on("click", function(event){
var url = this.getAttribute('href');
event.preventDefault();
//-- Provide the Book with the url to show
// The Url must be found in the books manifest
rendition.display(url);
$list.find(".currentChapter")
.addClass("openChapter")
.removeClass("currentChapter");
$(this).parent('li').addClass("currentChapter");
});
$list.find(".toc_toggle").on("click", function(event){
var $el = $(this).parent('li'),
open = $el.hasClass("openChapter");
event.preventDefault();
if(open){
$el.removeClass("openChapter");
} else {
$el.addClass("openChapter");
}
});
return {
"show" : onShow,
"hide" : onHide
};
};
//# sourceMappingURL=reader.js.map | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/reader.js | reader.js |
window.hypothesisConfig = function() {
var Annotator = window.Annotator;
var $main = $("#main");
function EpubAnnotationSidebar(elem, options) {
options = {
server: true,
origin: true,
showHighlights: true,
Toolbar: {container: '#annotation-controls'}
}
Annotator.Host.call(this, elem, options);
}
EpubAnnotationSidebar.prototype = Object.create(Annotator.Host.prototype);
EpubAnnotationSidebar.prototype.show = function() {
this.frame.css({
'margin-left': (-1 * this.frame.width()) + "px"
});
this.frame.removeClass('annotator-collapsed');
if (!$main.hasClass('single')) {
$main.addClass("single");
this.toolbar.find('[name=sidebar-toggle]').removeClass('h-icon-chevron-left').addClass('h-icon-chevron-right');
this.setVisibleHighlights(true);
}
};
EpubAnnotationSidebar.prototype.hide = function() {
this.frame.css({
'margin-left': ''
});
this.frame.addClass('annotator-collapsed');
if ($main.hasClass('single')) {
$main.removeClass("single");
this.toolbar.find('[name=sidebar-toggle]').removeClass('h-icon-chevron-right').addClass('h-icon-chevron-left');
this.setVisibleHighlights(false);
}
};
return {
constructor: EpubAnnotationSidebar,
}
};
// This is the Epub.js plugin. Annotations are updated on location change.
EPUBJS.reader.plugins.HypothesisController = function (Book) {
var reader = this;
var $main = $("#main");
var updateAnnotations = function () {
var annotator = Book.renderer.render.window.annotator;
if (annotator && annotator.constructor.$) {
var annotations = getVisibleAnnotations(annotator.constructor.$);
annotator.showAnnotations(annotations)
}
};
var getVisibleAnnotations = function ($) {
var width = Book.renderer.render.iframe.clientWidth;
return $('.annotator-hl').map(function() {
var $this = $(this),
left = this.getBoundingClientRect().left;
if (left >= 0 && left <= width) {
return $this.data('annotation');
}
}).get();
};
Book.on("renderer:locationChanged", updateAnnotations);
return {}
}; | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/plugins/hypothesis.js | hypothesis.js |
EPUBJS.reader.search = {};
// Search Server -- https://github.com/futurepress/epubjs-search
EPUBJS.reader.search.SERVER = "https://pacific-cliffs-3579.herokuapp.com";
EPUBJS.reader.search.request = function(q, callback) {
var fetch = $.ajax({
dataType: "json",
url: EPUBJS.reader.search.SERVER + "/search?q=" + encodeURIComponent(q)
});
fetch.fail(function(err) {
console.error(err);
});
fetch.done(function(results) {
callback(results);
});
};
EPUBJS.reader.plugins.SearchController = function(Book) {
var reader = this;
var $searchBox = $("#searchBox"),
$searchResults = $("#searchResults"),
$searchView = $("#searchView"),
iframeDoc;
var searchShown = false;
var onShow = function() {
query();
searchShown = true;
$searchView.addClass("shown");
};
var onHide = function() {
searchShown = false;
$searchView.removeClass("shown");
};
var query = function() {
var q = $searchBox.val();
if(q == '') {
return;
}
$searchResults.empty();
$searchResults.append("<li><p>Searching...</p></li>");
EPUBJS.reader.search.request(q, function(data) {
var results = data.results;
$searchResults.empty();
if(iframeDoc) {
$(iframeDoc).find('body').unhighlight();
}
if(results.length == 0) {
$searchResults.append("<li><p>No Results Found</p></li>");
return;
}
iframeDoc = $("#viewer iframe")[0].contentDocument;
$(iframeDoc).find('body').highlight(q, { element: 'span' });
results.forEach(function(result) {
var $li = $("<li></li>");
var $item = $("<a href='"+result.href+"' data-cfi='"+result.cfi+"'><span>"+result.title+"</span><p>"+result.highlight+"</p></a>");
$item.on("click", function(e) {
var $this = $(this),
cfi = $this.data("cfi");
e.preventDefault();
Book.gotoCfi(cfi+"/1:0");
Book.on("renderer:chapterDisplayed", function() {
iframeDoc = $("#viewer iframe")[0].contentDocument;
$(iframeDoc).find('body').highlight(q, { element: 'span' });
})
});
$li.append($item);
$searchResults.append($li);
});
});
};
$searchBox.on("search", function(e) {
var q = $searchBox.val();
//-- SearchBox is empty or cleared
if(q == '') {
$searchResults.empty();
if(reader.SidebarController.getActivePanel() == "Search") {
reader.SidebarController.changePanelTo("Toc");
}
$(iframeDoc).find('body').unhighlight();
iframeDoc = false;
return;
}
reader.SidebarController.changePanelTo("Search");
e.preventDefault();
});
return {
"show" : onShow,
"hide" : onHide
};
}; | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/plugins/search.js | search.js |
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){"use strict";var d=a("./utils"),e=a("./support"),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";c.encode=function(a){for(var b,c,e,g,h,i,j,k=[],l=0,m=a.length,n=m,o="string"!==d.getTypeOf(a);l<a.length;)n=m-l,o?(b=a[l++],c=l<m?a[l++]:0,e=l<m?a[l++]:0):(b=a.charCodeAt(l++),c=l<m?a.charCodeAt(l++):0,e=l<m?a.charCodeAt(l++):0),g=b>>2,h=(3&b)<<4|c>>4,i=n>1?(15&c)<<2|e>>6:64,j=n>2?63&e:64,k.push(f.charAt(g)+f.charAt(h)+f.charAt(i)+f.charAt(j));return k.join("")},c.decode=function(a){var b,c,d,g,h,i,j,k=0,l=0,m="data:";if(a.substr(0,m.length)===m)throw new Error("Invalid base64 input, it looks like a data url.");a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");var n=3*a.length/4;if(a.charAt(a.length-1)===f.charAt(64)&&n--,a.charAt(a.length-2)===f.charAt(64)&&n--,n%1!==0)throw new Error("Invalid base64 input, bad content length.");var o;for(o=e.uint8array?new Uint8Array(0|n):new Array(0|n);k<a.length;)g=f.indexOf(a.charAt(k++)),h=f.indexOf(a.charAt(k++)),i=f.indexOf(a.charAt(k++)),j=f.indexOf(a.charAt(k++)),b=g<<2|h>>4,c=(15&h)<<4|i>>2,d=(3&i)<<6|j,o[l++]=b,64!==i&&(o[l++]=c),64!==j&&(o[l++]=d);return o}},{"./support":30,"./utils":32}],2:[function(a,b,c){"use strict";function d(a,b,c,d,e){this.compressedSize=a,this.uncompressedSize=b,this.crc32=c,this.compression=d,this.compressedContent=e}var e=a("./external"),f=a("./stream/DataWorker"),g=a("./stream/DataLengthProbe"),h=a("./stream/Crc32Probe"),g=a("./stream/DataLengthProbe");d.prototype={getContentWorker:function(){var a=new f(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new g("data_length")),b=this;return a.on("end",function(){if(this.streamInfo.data_length!==b.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new f(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(a,b,c){return a.pipe(new h).pipe(new g("uncompressedSize")).pipe(b.compressWorker(c)).pipe(new g("compressedSize")).withStreamInfo("compression",b)},b.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(a,b,c){"use strict";var d=a("./stream/GenericWorker");c.STORE={magic:"\0\0",compressWorker:function(a){return new d("STORE compression")},uncompressWorker:function(){return new d("STORE decompression")}},c.DEFLATE=a("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;c<256;c++){a=c;for(var d=0;d<8;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=h,f=d+c;a^=-1;for(var g=d;g<f;g++)a=a>>>8^e[255&(a^b[g])];return a^-1}function f(a,b,c,d){var e=h,f=d+c;a^=-1;for(var g=d;g<f;g++)a=a>>>8^e[255&(a^b.charCodeAt(g))];return a^-1}var g=a("./utils"),h=d();b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var c="string"!==g.getTypeOf(a);return c?e(0|b,a,a.length,0):f(0|b,a,a.length,0)}},{"./utils":32}],5:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!0,c.date=null,c.compression=null,c.compressionOptions=null,c.comment=null,c.unixPermissions=null,c.dosPermissions=null},{}],6:[function(a,b,c){"use strict";var d=null;d="undefined"!=typeof Promise?Promise:a("lie"),b.exports={Promise:d}},{lie:58}],7:[function(a,b,c){"use strict";function d(a,b){h.call(this,"FlateWorker/"+a),this._pako=null,this._pakoAction=a,this._pakoOptions=b,this.meta={}}var e="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,f=a("pako"),g=a("./utils"),h=a("./stream/GenericWorker"),i=e?"uint8array":"array";c.magic="\b\0",g.inherits(d,h),d.prototype.processChunk=function(a){this.meta=a.meta,null===this._pako&&this._createPako(),this._pako.push(g.transformTo(i,a.data),!1)},d.prototype.flush=function(){h.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},d.prototype.cleanUp=function(){h.prototype.cleanUp.call(this),this._pako=null},d.prototype._createPako=function(){this._pako=new f[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var a=this;this._pako.onData=function(b){a.push({data:b,meta:a.meta})}},c.compressWorker=function(a){return new d("Deflate",a)},c.uncompressWorker=function(){return new d("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:59}],8:[function(a,b,c){"use strict";function d(a,b,c,d){f.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=b,this.zipPlatform=c,this.encodeFileName=d,this.streamFiles=a,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}var e=a("../utils"),f=a("../stream/GenericWorker"),g=a("../utf8"),h=a("../crc32"),i=a("../signature"),j=function(a,b){var c,d="";for(c=0;c<b;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},k=function(a,b){var c=a;return a||(c=b?16893:33204),(65535&c)<<16},l=function(a,b){return 63&(a||0)},m=function(a,b,c,d,f,m){var n,o,p=a.file,q=a.compression,r=m!==g.utf8encode,s=e.transformTo("string",m(p.name)),t=e.transformTo("string",g.utf8encode(p.name)),u=p.comment,v=e.transformTo("string",m(u)),w=e.transformTo("string",g.utf8encode(u)),x=t.length!==p.name.length,y=w.length!==u.length,z="",A="",B="",C=p.dir,D=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};b&&!c||(E.crc32=a.crc32,E.compressedSize=a.compressedSize,E.uncompressedSize=a.uncompressedSize);var F=0;b&&(F|=8),r||!x&&!y||(F|=2048);var G=0,H=0;C&&(G|=16),"UNIX"===f?(H=798,G|=k(p.unixPermissions,C)):(H=20,G|=l(p.dosPermissions,C)),n=D.getUTCHours(),n<<=6,n|=D.getUTCMinutes(),n<<=5,n|=D.getUTCSeconds()/2,o=D.getUTCFullYear()-1980,o<<=4,o|=D.getUTCMonth()+1,o<<=5,o|=D.getUTCDate(),x&&(A=j(1,1)+j(h(s),4)+t,z+="up"+j(A.length,2)+A),y&&(B=j(1,1)+j(h(v),4)+w,z+="uc"+j(B.length,2)+B);var I="";I+="\n\0",I+=j(F,2),I+=q.magic,I+=j(n,2),I+=j(o,2),I+=j(E.crc32,4),I+=j(E.compressedSize,4),I+=j(E.uncompressedSize,4),I+=j(s.length,2),I+=j(z.length,2);var J=i.LOCAL_FILE_HEADER+I+s+z,K=i.CENTRAL_FILE_HEADER+j(H,2)+I+j(v.length,2)+"\0\0\0\0"+j(G,4)+j(d,4)+s+z+v;return{fileRecord:J,dirRecord:K}},n=function(a,b,c,d,f){var g="",h=e.transformTo("string",f(d));return g=i.CENTRAL_DIRECTORY_END+"\0\0\0\0"+j(a,2)+j(a,2)+j(b,4)+j(c,4)+j(h.length,2)+h},o=function(a){var b="";return b=i.DATA_DESCRIPTOR+j(a.crc32,4)+j(a.compressedSize,4)+j(a.uncompressedSize,4)};e.inherits(d,f),d.prototype.push=function(a){var b=a.meta.percent||0,c=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(a):(this.bytesWritten+=a.data.length,f.prototype.push.call(this,{data:a.data,meta:{currentFile:this.currentFile,percent:c?(b+100*(c-d-1))/c:100}}))},d.prototype.openedSource=function(a){this.currentSourceOffset=this.bytesWritten,this.currentFile=a.file.name;var b=this.streamFiles&&!a.file.dir;if(b){var c=m(a,b,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:c.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(a){this.accumulate=!1;var b=this.streamFiles&&!a.file.dir,c=m(a,b,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(c.dirRecord),b)this.push({data:o(a),meta:{percent:100}});else for(this.push({data:c.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var a=this.bytesWritten,b=0;b<this.dirRecords.length;b++)this.push({data:this.dirRecords[b],meta:{percent:100}});var c=this.bytesWritten-a,d=n(this.dirRecords.length,c,a,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},d.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},d.prototype.registerPrevious=function(a){this._sources.push(a);var b=this;return a.on("data",function(a){b.processChunk(a)}),a.on("end",function(){b.closedSource(b.previous.streamInfo),b._sources.length?b.prepareNextSource():b.end()}),a.on("error",function(a){b.error(a)}),this},d.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},d.prototype.error=function(a){var b=this._sources;if(!f.prototype.error.call(this,a))return!1;for(var c=0;c<b.length;c++)try{b[c].error(a)}catch(a){}return!0},d.prototype.lock=function(){f.prototype.lock.call(this);for(var a=this._sources,b=0;b<a.length;b++)a[b].lock()},b.exports=d},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(a,b,c){"use strict";var d=a("../compressions"),e=a("./ZipFileWorker"),f=function(a,b){var c=a||b,e=d[c];if(!e)throw new Error(c+" is not a valid compression method !");return e};c.generateWorker=function(a,b,c){var d=new e(b.streamFiles,c,b.platform,b.encodeFileName),g=0;try{a.forEach(function(a,c){g++;var e=f(c.options.compression,b.compression),h=c.options.compressionOptions||b.compressionOptions||{},i=c.dir,j=c.date;c._compressWorker(e,h).withStreamInfo("file",{name:a,dir:i,date:j,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(d)}),d.entriesCount=g}catch(h){d.error(h)}return d}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(a,b,c){"use strict";function d(){if(!(this instanceof d))return new d;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files={},this.comment=null,this.root="",this.clone=function(){var a=new d;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a}}d.prototype=a("./object"),d.prototype.loadAsync=a("./load"),d.support=a("./support"),d.defaults=a("./defaults"),d.version="3.1.5",d.loadAsync=function(a,b){return(new d).loadAsync(a,b)},d.external=a("./external"),b.exports=d},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(a,b,c){"use strict";function d(a){return new f.Promise(function(b,c){var d=a.decompressed.getContentWorker().pipe(new i);d.on("error",function(a){c(a)}).on("end",function(){d.streamInfo.crc32!==a.decompressed.crc32?c(new Error("Corrupted zip : CRC32 mismatch")):b()}).resume()})}var e=a("./utils"),f=a("./external"),g=a("./utf8"),e=a("./utils"),h=a("./zipEntries"),i=a("./stream/Crc32Probe"),j=a("./nodejsUtils");b.exports=function(a,b){var c=this;return b=e.extend(b||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:g.utf8decode}),j.isNode&&j.isStream(a)?f.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",a,!0,b.optimizedBinaryString,b.base64).then(function(a){var c=new h(b);return c.load(a),c}).then(function(a){var c=[f.Promise.resolve(a)],e=a.files;if(b.checkCRC32)for(var g=0;g<e.length;g++)c.push(d(e[g]));return f.Promise.all(c)}).then(function(a){for(var d=a.shift(),e=d.files,f=0;f<e.length;f++){var g=e[f];c.file(g.fileNameStr,g.decompressed,{binary:!0,optimizedBinaryString:!0,date:g.date,dir:g.dir,comment:g.fileCommentStr.length?g.fileCommentStr:null,unixPermissions:g.unixPermissions,dosPermissions:g.dosPermissions,createFolders:b.createFolders})}return d.zipComment.length&&(c.comment=d.zipComment),c})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(a,b,c){"use strict";function d(a,b){f.call(this,"Nodejs stream input adapter for "+a),this._upstreamEnded=!1,this._bindStream(b)}var e=a("../utils"),f=a("../stream/GenericWorker");e.inherits(d,f),d.prototype._bindStream=function(a){var b=this;this._stream=a,a.pause(),a.on("data",function(a){b.push({data:a,meta:{percent:0}})}).on("error",function(a){b.isPaused?this.generatedError=a:b.error(a)}).on("end",function(){b.isPaused?b._upstreamEnded=!0:b.end()})},d.prototype.pause=function(){return!!f.prototype.pause.call(this)&&(this._stream.pause(),!0)},d.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},b.exports=d},{"../stream/GenericWorker":28,"../utils":32}],13:[function(a,b,c){"use strict";function d(a,b,c){e.call(this,b),this._helper=a;var d=this;a.on("data",function(a,b){d.push(a)||d._helper.pause(),c&&c(b)}).on("error",function(a){d.emit("error",a)}).on("end",function(){d.push(null)})}var e=a("readable-stream").Readable,f=a("../utils");f.inherits(d,e),d.prototype._read=function(){this._helper.resume()},b.exports=d},{"../utils":32,"readable-stream":16}],14:[function(a,b,c){"use strict";b.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(a,b){return new Buffer(a,b)},allocBuffer:function(a){return Buffer.alloc?Buffer.alloc(a):new Buffer(a)},isBuffer:function(a){return Buffer.isBuffer(a)},isStream:function(a){return a&&"function"==typeof a.on&&"function"==typeof a.pause&&"function"==typeof a.resume}}},{}],15:[function(a,b,c){"use strict";function d(a){return"[object RegExp]"===Object.prototype.toString.call(a)}var e=a("./utf8"),f=a("./utils"),g=a("./stream/GenericWorker"),h=a("./stream/StreamHelper"),i=a("./defaults"),j=a("./compressedObject"),k=a("./zipObject"),l=a("./generate"),m=a("./nodejsUtils"),n=a("./nodejs/NodejsStreamInputAdapter"),o=function(a,b,c){var d,e=f.getTypeOf(b),h=f.extend(c||{},i);h.date=h.date||new Date,null!==h.compression&&(h.compression=h.compression.toUpperCase()),"string"==typeof h.unixPermissions&&(h.unixPermissions=parseInt(h.unixPermissions,8)),h.unixPermissions&&16384&h.unixPermissions&&(h.dir=!0),h.dosPermissions&&16&h.dosPermissions&&(h.dir=!0),h.dir&&(a=q(a)),h.createFolders&&(d=p(a))&&r.call(this,d,!0);var l="string"===e&&h.binary===!1&&h.base64===!1;c&&"undefined"!=typeof c.binary||(h.binary=!l);var o=b instanceof j&&0===b.uncompressedSize;(o||h.dir||!b||0===b.length)&&(h.base64=!1,h.binary=!0,b="",h.compression="STORE",e="string");var s=null;s=b instanceof j||b instanceof g?b:m.isNode&&m.isStream(b)?new n(a,b):f.prepareContent(a,b,h.binary,h.optimizedBinaryString,h.base64);var t=new k(a,s,h);this.files[a]=t},p=function(a){"/"===a.slice(-1)&&(a=a.substring(0,a.length-1));var b=a.lastIndexOf("/");return b>0?a.substring(0,b):""},q=function(a){return"/"!==a.slice(-1)&&(a+="/"),a},r=function(a,b){return b="undefined"!=typeof b?b:i.createFolders,a=q(a),this.files[a]||o.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},s={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(a){var b,c,d;for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],c=b.slice(this.root.length,b.length),c&&b.slice(0,this.root.length)===this.root&&a(c,d))},filter:function(a){var b=[];return this.forEach(function(c,d){a(c,d)&&b.push(d)}),b},file:function(a,b,c){if(1===arguments.length){if(d(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}var f=this.files[this.root+a];return f&&!f.dir?f:null}return a=this.root+a,o.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=r.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!==a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d<c.length;d++)delete this.files[c[d].name];return this},generate:function(a){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(a){var b,c={};try{if(c=f.extend(a||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:e.utf8encode}),c.type=c.type.toLowerCase(),c.compression=c.compression.toUpperCase(),"binarystring"===c.type&&(c.type="string"),!c.type)throw new Error("No output type specified.");f.checkSupport(c.type),"darwin"!==c.platform&&"freebsd"!==c.platform&&"linux"!==c.platform&&"sunos"!==c.platform||(c.platform="UNIX"),"win32"===c.platform&&(c.platform="DOS");var d=c.comment||this.comment||"";b=l.generateWorker(this,c,d)}catch(i){b=new g("error"),b.error(i)}return new h(b,c.type||"string",c.mimeType)},generateAsync:function(a,b){return this.generateInternalStream(a).accumulate(b)},generateNodeStream:function(a,b){return a=a||{},a.type||(a.type="nodebuffer"),this.generateInternalStream(a).toNodejsStream(b)}};b.exports=s},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(a,b,c){b.exports=a("stream")},{stream:void 0}],17:[function(a,b,c){"use strict";function d(a){e.call(this,a);for(var b=0;b<this.data.length;b++)a[b]=255&a[b]}var e=a("./DataReader"),f=a("../utils");f.inherits(d,e),d.prototype.byteAt=function(a){return this.data[this.zero+a]},d.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f-this.zero;return-1},d.prototype.readAndCheckSignature=function(a){var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.readData(4);return b===f[0]&&c===f[1]&&d===f[2]&&e===f[3]},d.prototype.readData=function(a){if(this.checkOffset(a),0===a)return[];var b=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./DataReader":18}],18:[function(a,b,c){"use strict";function d(a){this.data=a,this.length=a.length,this.index=0,this.zero=0}var e=a("../utils");d.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.length<this.zero+a||a<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(a){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return e.transformTo("string",this.readData(a))},readData:function(a){},lastIndexOfSignature:function(a){},readAndCheckSignature:function(a){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},b.exports=d},{"../utils":32}],19:[function(a,b,c){"use strict";function d(a){e.call(this,a)}var e=a("./Uint8ArrayReader"),f=a("../utils");f.inherits(d,e),d.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(a,b,c){"use strict";function d(a){e.call(this,a)}var e=a("./DataReader"),f=a("../utils");f.inherits(d,e),d.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},d.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},d.prototype.readAndCheckSignature=function(a){var b=this.readData(4);return a===b},d.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./DataReader":18}],21:[function(a,b,c){"use strict";function d(a){e.call(this,a)}var e=a("./ArrayReader"),f=a("../utils");f.inherits(d,e),d.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./ArrayReader":17}],22:[function(a,b,c){"use strict";var d=a("../utils"),e=a("../support"),f=a("./ArrayReader"),g=a("./StringReader"),h=a("./NodeBufferReader"),i=a("./Uint8ArrayReader");b.exports=function(a){var b=d.getTypeOf(a);return d.checkSupport(b),"string"!==b||e.uint8array?"nodebuffer"===b?new h(a):e.uint8array?new i(d.transformTo("uint8array",a)):new f(d.transformTo("array",a)):new g(a)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(a,b,c){"use strict";c.LOCAL_FILE_HEADER="PK",c.CENTRAL_FILE_HEADER="PK",c.CENTRAL_DIRECTORY_END="PK",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",c.ZIP64_CENTRAL_DIRECTORY_END="PK",c.DATA_DESCRIPTOR="PK\b"},{}],24:[function(a,b,c){"use strict";function d(a){e.call(this,"ConvertWorker to "+a),this.destType=a}var e=a("./GenericWorker"),f=a("../utils");f.inherits(d,e),d.prototype.processChunk=function(a){this.push({data:f.transformTo(this.destType,a.data),meta:a.meta})},b.exports=d},{"../utils":32,"./GenericWorker":28}],25:[function(a,b,c){"use strict";function d(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}var e=a("./GenericWorker"),f=a("../crc32"),g=a("../utils");g.inherits(d,e),d.prototype.processChunk=function(a){this.streamInfo.crc32=f(a.data,this.streamInfo.crc32||0),this.push(a)},b.exports=d},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(a,b,c){"use strict";function d(a){f.call(this,"DataLengthProbe for "+a),this.propName=a,this.withStreamInfo(a,0)}var e=a("../utils"),f=a("./GenericWorker");e.inherits(d,f),d.prototype.processChunk=function(a){if(a){var b=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=b+a.data.length}f.prototype.processChunk.call(this,a)},b.exports=d},{"../utils":32,"./GenericWorker":28}],27:[function(a,b,c){"use strict";function d(a){f.call(this,"DataWorker");var b=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,a.then(function(a){b.dataIsReady=!0,b.data=a,b.max=a&&a.length||0,b.type=e.getTypeOf(a),b.isPaused||b._tickAndRepeat()},function(a){b.error(a)})}var e=a("../utils"),f=a("./GenericWorker"),g=16384;e.inherits(d,f),d.prototype.cleanUp=function(){f.prototype.cleanUp.call(this),this.data=null},d.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},d.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},d.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var a=g,b=null,c=Math.min(this.max,this.index+a);if(this.index>=this.max)return this.end();switch(this.type){case"string":b=this.data.substring(this.index,c);break;case"uint8array":b=this.data.subarray(this.index,c);break;case"array":case"nodebuffer":b=this.data.slice(this.index,c)}return this.index=c,this.push({data:b,meta:{percent:this.max?this.index/this.max*100:0}})},b.exports=d},{"../utils":32,"./GenericWorker":28}],28:[function(a,b,c){"use strict";function d(a){this.name=a||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}d.prototype={push:function(a){this.emit("data",a)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(a){this.emit("error",a)}return!0},error:function(a){return!this.isFinished&&(this.isPaused?this.generatedError=a:(this.isFinished=!0,this.emit("error",a),this.previous&&this.previous.error(a),this.cleanUp()),!0)},on:function(a,b){return this._listeners[a].push(b),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(a,b){if(this._listeners[a])for(var c=0;c<this._listeners[a].length;c++)this._listeners[a][c].call(this,b)},pipe:function(a){return a.registerPrevious(this)},registerPrevious:function(a){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=a.streamInfo,this.mergeStreamInfo(),this.previous=a;var b=this;return a.on("data",function(a){b.processChunk(a)}),a.on("end",function(){b.end()}),a.on("error",function(a){b.error(a)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;this.isPaused=!1;var a=!1;return this.generatedError&&(this.error(this.generatedError),a=!0),this.previous&&this.previous.resume(),!a},flush:function(){},processChunk:function(a){this.push(a)},withStreamInfo:function(a,b){return this.extraStreamInfo[a]=b,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var a in this.extraStreamInfo)this.extraStreamInfo.hasOwnProperty(a)&&(this.streamInfo[a]=this.extraStreamInfo[a])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var a="Worker "+this.name;return this.previous?this.previous+" -> "+a:a}},b.exports=d},{}],29:[function(a,b,c){"use strict";function d(a,b,c){switch(a){case"blob":return h.newBlob(h.transformTo("arraybuffer",b),c);case"base64":return k.encode(b);default:return h.transformTo(a,b)}}function e(a,b){var c,d=0,e=null,f=0;for(c=0;c<b.length;c++)f+=b[c].length;switch(a){case"string":return b.join("");case"array":return Array.prototype.concat.apply([],b);case"uint8array":for(e=new Uint8Array(f),c=0;c<b.length;c++)e.set(b[c],d),d+=b[c].length;return e;case"nodebuffer":return Buffer.concat(b);default:throw new Error("concat : unsupported type '"+a+"'")}}function f(a,b){return new m.Promise(function(c,f){var g=[],h=a._internalType,i=a._outputType,j=a._mimeType;a.on("data",function(a,c){g.push(a),b&&b(c)}).on("error",function(a){g=[],f(a)}).on("end",function(){try{var a=d(i,e(h,g),j);c(a)}catch(b){f(b)}g=[]}).resume()})}function g(a,b,c){var d=b;switch(b){case"blob":case"arraybuffer":d="uint8array";break;case"base64":d="string"}try{this._internalType=d,this._outputType=b,this._mimeType=c,h.checkSupport(d),this._worker=a.pipe(new i(d)),a.lock()}catch(e){this._worker=new j("error"),this._worker.error(e)}}var h=a("../utils"),i=a("./ConvertWorker"),j=a("./GenericWorker"),k=a("../base64"),l=a("../support"),m=a("../external"),n=null;if(l.nodestream)try{n=a("../nodejs/NodejsStreamOutputAdapter")}catch(o){}g.prototype={accumulate:function(a){return f(this,a)},on:function(a,b){var c=this;return"data"===a?this._worker.on(a,function(a){b.call(c,a.data,a.meta)}):this._worker.on(a,function(){h.delay(b,arguments,c)}),this},resume:function(){return h.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(a){if(h.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new n(this,{objectMode:"nodebuffer"!==this._outputType},a)}},b.exports=g},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(a,b,c){"use strict";if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,c.nodebuffer="undefined"!=typeof Buffer,c.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)c.blob=!1;else{var d=new ArrayBuffer(0);try{c.blob=0===new Blob([d],{type:"application/zip"}).size}catch(e){try{var f=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,g=new f;g.append(d),c.blob=0===g.getBlob("application/zip").size}catch(e){c.blob=!1}}}try{c.nodestream=!!a("readable-stream").Readable}catch(e){c.nodestream=!1}},{"readable-stream":16}],31:[function(a,b,c){"use strict";function d(){i.call(this,"utf-8 decode"),this.leftOver=null}function e(){i.call(this,"utf-8 encode")}for(var f=a("./utils"),g=a("./support"),h=a("./nodejsUtils"),i=a("./stream/GenericWorker"),j=new Array(256),k=0;k<256;k++)j[k]=k>=252?6:k>=248?5:k>=240?4:k>=224?3:k>=192?2:1;j[254]=j[254]=1;var l=function(a){var b,c,d,e,f,h=a.length,i=0;for(e=0;e<h;e++)c=a.charCodeAt(e),55296===(64512&c)&&e+1<h&&(d=a.charCodeAt(e+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),e++)),i+=c<128?1:c<2048?2:c<65536?3:4;for(b=g.uint8array?new Uint8Array(i):new Array(i),f=0,e=0;f<i;e++)c=a.charCodeAt(e),55296===(64512&c)&&e+1<h&&(d=a.charCodeAt(e+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),e++)),c<128?b[f++]=c:c<2048?(b[f++]=192|c>>>6,b[f++]=128|63&c):c<65536?(b[f++]=224|c>>>12,b[f++]=128|c>>>6&63,b[f++]=128|63&c):(b[f++]=240|c>>>18,b[f++]=128|c>>>12&63,b[f++]=128|c>>>6&63,b[f++]=128|63&c);return b},m=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return c<0?b:0===c?b:c+j[a[c]]>b?c:b},n=function(a){var b,c,d,e,g=a.length,h=new Array(2*g);for(c=0,b=0;b<g;)if(d=a[b++],d<128)h[c++]=d;else if(e=j[d],e>4)h[c++]=65533,b+=e-1;else{for(d&=2===e?31:3===e?15:7;e>1&&b<g;)d=d<<6|63&a[b++],e--;e>1?h[c++]=65533:d<65536?h[c++]=d:(d-=65536,h[c++]=55296|d>>10&1023,h[c++]=56320|1023&d)}return h.length!==c&&(h.subarray?h=h.subarray(0,c):h.length=c),f.applyFromCharCode(h)};c.utf8encode=function(a){return g.nodebuffer?h.newBufferFrom(a,"utf-8"):l(a)},c.utf8decode=function(a){return g.nodebuffer?f.transformTo("nodebuffer",a).toString("utf-8"):(a=f.transformTo(g.uint8array?"uint8array":"array",a),n(a))},f.inherits(d,i),d.prototype.processChunk=function(a){var b=f.transformTo(g.uint8array?"uint8array":"array",a.data);if(this.leftOver&&this.leftOver.length){if(g.uint8array){var d=b;b=new Uint8Array(d.length+this.leftOver.length),b.set(this.leftOver,0),b.set(d,this.leftOver.length)}else b=this.leftOver.concat(b);this.leftOver=null}var e=m(b),h=b;e!==b.length&&(g.uint8array?(h=b.subarray(0,e),this.leftOver=b.subarray(e,b.length)):(h=b.slice(0,e),this.leftOver=b.slice(e,b.length))),this.push({data:c.utf8decode(h),meta:a.meta})},d.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:c.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},c.Utf8DecodeWorker=d,f.inherits(e,i),e.prototype.processChunk=function(a){this.push({data:c.utf8encode(a.data),meta:a.meta})},c.Utf8EncodeWorker=e},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(a,b,c){"use strict";function d(a){var b=null;return b=i.uint8array?new Uint8Array(a.length):new Array(a.length),f(a,b)}function e(a){return a}function f(a,b){for(var c=0;c<a.length;++c)b[c]=255&a.charCodeAt(c);return b}function g(a){var b=65536,d=c.getTypeOf(a),e=!0;if("uint8array"===d?e=n.applyCanBeUsed.uint8array:"nodebuffer"===d&&(e=n.applyCanBeUsed.nodebuffer),e)for(;b>1;)try{return n.stringifyByChunk(a,d,b)}catch(f){b=Math.floor(b/2)}return n.stringifyByChar(a)}function h(a,b){for(var c=0;c<a.length;c++)b[c]=a[c];
return b}var i=a("./support"),j=a("./base64"),k=a("./nodejsUtils"),l=a("core-js/library/fn/set-immediate"),m=a("./external");c.newBlob=function(a,b){c.checkSupport("blob");try{return new Blob([a],{type:b})}catch(d){try{var e=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,f=new e;return f.append(a),f.getBlob(b)}catch(d){throw new Error("Bug : can't construct the Blob.")}}};var n={stringifyByChunk:function(a,b,c){var d=[],e=0,f=a.length;if(f<=c)return String.fromCharCode.apply(null,a);for(;e<f;)"array"===b||"nodebuffer"===b?d.push(String.fromCharCode.apply(null,a.slice(e,Math.min(e+c,f)))):d.push(String.fromCharCode.apply(null,a.subarray(e,Math.min(e+c,f)))),e+=c;return d.join("")},stringifyByChar:function(a){for(var b="",c=0;c<a.length;c++)b+=String.fromCharCode(a[c]);return b},applyCanBeUsed:{uint8array:function(){try{return i.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(a){return!1}}(),nodebuffer:function(){try{return i.nodebuffer&&1===String.fromCharCode.apply(null,k.allocBuffer(1)).length}catch(a){return!1}}()}};c.applyFromCharCode=g;var o={};o.string={string:e,array:function(a){return f(a,new Array(a.length))},arraybuffer:function(a){return o.string.uint8array(a).buffer},uint8array:function(a){return f(a,new Uint8Array(a.length))},nodebuffer:function(a){return f(a,k.allocBuffer(a.length))}},o.array={string:g,array:e,arraybuffer:function(a){return new Uint8Array(a).buffer},uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return k.newBufferFrom(a)}},o.arraybuffer={string:function(a){return g(new Uint8Array(a))},array:function(a){return h(new Uint8Array(a),new Array(a.byteLength))},arraybuffer:e,uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return k.newBufferFrom(new Uint8Array(a))}},o.uint8array={string:g,array:function(a){return h(a,new Array(a.length))},arraybuffer:function(a){return a.buffer},uint8array:e,nodebuffer:function(a){return k.newBufferFrom(a)}},o.nodebuffer={string:g,array:function(a){return h(a,new Array(a.length))},arraybuffer:function(a){return o.nodebuffer.uint8array(a).buffer},uint8array:function(a){return h(a,new Uint8Array(a.length))},nodebuffer:e},c.transformTo=function(a,b){if(b||(b=""),!a)return b;c.checkSupport(a);var d=c.getTypeOf(b),e=o[d][a](b);return e},c.getTypeOf=function(a){return"string"==typeof a?"string":"[object Array]"===Object.prototype.toString.call(a)?"array":i.nodebuffer&&k.isBuffer(a)?"nodebuffer":i.uint8array&&a instanceof Uint8Array?"uint8array":i.arraybuffer&&a instanceof ArrayBuffer?"arraybuffer":void 0},c.checkSupport=function(a){var b=i[a.toLowerCase()];if(!b)throw new Error(a+" is not supported by this platform")},c.MAX_VALUE_16BITS=65535,c.MAX_VALUE_32BITS=-1,c.pretty=function(a){var b,c,d="";for(c=0;c<(a||"").length;c++)b=a.charCodeAt(c),d+="\\x"+(b<16?"0":"")+b.toString(16).toUpperCase();return d},c.delay=function(a,b,c){l(function(){a.apply(c||null,b||[])})},c.inherits=function(a,b){var c=function(){};c.prototype=b.prototype,a.prototype=new c},c.extend=function(){var a,b,c={};for(a=0;a<arguments.length;a++)for(b in arguments[a])arguments[a].hasOwnProperty(b)&&"undefined"==typeof c[b]&&(c[b]=arguments[a][b]);return c},c.prepareContent=function(a,b,e,f,g){var h=m.Promise.resolve(b).then(function(a){var b=i.blob&&(a instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(a))!==-1);return b&&"undefined"!=typeof FileReader?new m.Promise(function(b,c){var d=new FileReader;d.onload=function(a){b(a.target.result)},d.onerror=function(a){c(a.target.error)},d.readAsArrayBuffer(a)}):a});return h.then(function(b){var h=c.getTypeOf(b);return h?("arraybuffer"===h?b=c.transformTo("uint8array",b):"string"===h&&(g?b=j.decode(b):e&&f!==!0&&(b=d(b))),b):m.Promise.reject(new Error("Can't read the data of '"+a+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"core-js/library/fn/set-immediate":36}],33:[function(a,b,c){"use strict";function d(a){this.files=[],this.loadOptions=a}var e=a("./reader/readerFor"),f=a("./utils"),g=a("./signature"),h=a("./zipEntry"),i=(a("./utf8"),a("./support"));d.prototype={checkSignature:function(a){if(!this.reader.readAndCheckSignature(a)){this.reader.index-=4;var b=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+f.pretty(b)+", expected "+f.pretty(a)+")")}},isSignature:function(a,b){var c=this.reader.index;this.reader.setIndex(a);var d=this.reader.readString(4),e=d===b;return this.reader.setIndex(c),e},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var a=this.reader.readData(this.zipCommentLength),b=i.uint8array?"uint8array":"array",c=f.transformTo(b,a);this.zipComment=this.loadOptions.decodeFileName(c)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;e<d;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readData(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a<this.files.length;a++)b=this.files[a],this.reader.setIndex(b.localHeaderOffset),this.checkSignature(g.LOCAL_FILE_HEADER),b.readLocalPart(this.reader),b.handleUTF8(),b.processAttributes()},readCentralDir:function(){var a;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(g.CENTRAL_FILE_HEADER);)a=new h({zip64:this.zip64},this.loadOptions),a.readCentralPart(this.reader),this.files.push(a);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var a=this.reader.lastIndexOfSignature(g.CENTRAL_DIRECTORY_END);if(a<0){var b=!this.isSignature(0,g.LOCAL_FILE_HEADER);throw b?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(a);var c=a;if(this.checkSignature(g.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===f.MAX_VALUE_16BITS||this.diskWithCentralDirStart===f.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===f.MAX_VALUE_16BITS||this.centralDirRecords===f.MAX_VALUE_16BITS||this.centralDirSize===f.MAX_VALUE_32BITS||this.centralDirOffset===f.MAX_VALUE_32BITS){if(this.zip64=!0,a=this.reader.lastIndexOfSignature(g.ZIP64_CENTRAL_DIRECTORY_LOCATOR),a<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(a),this.checkSignature(g.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,g.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(g.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(g.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var d=this.centralDirOffset+this.centralDirSize;this.zip64&&(d+=20,d+=12+this.zip64EndOfCentralSize);var e=c-d;if(e>0)this.isSignature(c,g.CENTRAL_FILE_HEADER)||(this.reader.zero=e);else if(e<0)throw new Error("Corrupted zip: missing "+Math.abs(e)+" bytes.")},prepareReader:function(a){this.reader=e(a)},load:function(a){this.prepareReader(a),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},b.exports=d},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(a,b,c){"use strict";function d(a,b){this.options=a,this.loadOptions=b}var e=a("./reader/readerFor"),f=a("./utils"),g=a("./compressedObject"),h=a("./crc32"),i=a("./utf8"),j=a("./compressions"),k=a("./support"),l=0,m=3,n=function(a){for(var b in j)if(j.hasOwnProperty(b)&&j[b].magic===a)return j[b];return null};d.prototype={isEncrypted:function(){return 1===(1&this.bitFlag)},useUTF8:function(){return 2048===(2048&this.bitFlag)},readLocalPart:function(a){var b,c;if(a.skip(22),this.fileNameLength=a.readInt(2),c=a.readInt(2),this.fileName=a.readData(this.fileNameLength),a.skip(c),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(b=n(this.compressionMethod),null===b)throw new Error("Corrupted zip : compression "+f.pretty(this.compressionMethod)+" unknown (inner file : "+f.transformTo("string",this.fileName)+")");this.decompressed=new g(this.compressedSize,this.uncompressedSize,this.crc32,b,a.readData(this.compressedSize))},readCentralPart:function(a){this.versionMadeBy=a.readInt(2),a.skip(2),this.bitFlag=a.readInt(2),this.compressionMethod=a.readString(2),this.date=a.readDate(),this.crc32=a.readInt(4),this.compressedSize=a.readInt(4),this.uncompressedSize=a.readInt(4);var b=a.readInt(2);if(this.extraFieldsLength=a.readInt(2),this.fileCommentLength=a.readInt(2),this.diskNumberStart=a.readInt(2),this.internalFileAttributes=a.readInt(2),this.externalFileAttributes=a.readInt(4),this.localHeaderOffset=a.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");a.skip(b),this.readExtraFields(a),this.parseZIP64ExtraField(a),this.fileComment=a.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var a=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),a===l&&(this.dosPermissions=63&this.externalFileAttributes),a===m&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(a){if(this.extraFields[1]){var b=e(this.extraFields[1].value);this.uncompressedSize===f.MAX_VALUE_32BITS&&(this.uncompressedSize=b.readInt(8)),this.compressedSize===f.MAX_VALUE_32BITS&&(this.compressedSize=b.readInt(8)),this.localHeaderOffset===f.MAX_VALUE_32BITS&&(this.localHeaderOffset=b.readInt(8)),this.diskNumberStart===f.MAX_VALUE_32BITS&&(this.diskNumberStart=b.readInt(4))}},readExtraFields:function(a){var b,c,d,e=a.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});a.index<e;)b=a.readInt(2),c=a.readInt(2),d=a.readData(c),this.extraFields[b]={id:b,length:c,value:d}},handleUTF8:function(){var a=k.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=i.utf8decode(this.fileName),this.fileCommentStr=i.utf8decode(this.fileComment);else{var b=this.findExtraFieldUnicodePath();if(null!==b)this.fileNameStr=b;else{var c=f.transformTo(a,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(c)}var d=this.findExtraFieldUnicodeComment();if(null!==d)this.fileCommentStr=d;else{var e=f.transformTo(a,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(e)}}},findExtraFieldUnicodePath:function(){var a=this.extraFields[28789];if(a){var b=e(a.value);return 1!==b.readInt(1)?null:h(this.fileName)!==b.readInt(4)?null:i.utf8decode(b.readData(a.length-5))}return null},findExtraFieldUnicodeComment:function(){var a=this.extraFields[25461];if(a){var b=e(a.value);return 1!==b.readInt(1)?null:h(this.fileComment)!==b.readInt(4)?null:i.utf8decode(b.readData(a.length-5))}return null}},b.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(a,b,c){"use strict";var d=a("./stream/StreamHelper"),e=a("./stream/DataWorker"),f=a("./utf8"),g=a("./compressedObject"),h=a("./stream/GenericWorker"),i=function(a,b,c){this.name=a,this.dir=c.dir,this.date=c.date,this.comment=c.comment,this.unixPermissions=c.unixPermissions,this.dosPermissions=c.dosPermissions,this._data=b,this._dataBinary=c.binary,this.options={compression:c.compression,compressionOptions:c.compressionOptions}};i.prototype={internalStream:function(a){var b=null,c="string";try{if(!a)throw new Error("No output type specified.");c=a.toLowerCase();var e="string"===c||"text"===c;"binarystring"!==c&&"text"!==c||(c="string"),b=this._decompressWorker();var g=!this._dataBinary;g&&!e&&(b=b.pipe(new f.Utf8EncodeWorker)),!g&&e&&(b=b.pipe(new f.Utf8DecodeWorker))}catch(i){b=new h("error"),b.error(i)}return new d(b,c,"")},async:function(a,b){return this.internalStream(a).accumulate(b)},nodeStream:function(a,b){return this.internalStream(a||"nodebuffer").toNodejsStream(b)},_compressWorker:function(a,b){if(this._data instanceof g&&this._data.compression.magic===a.magic)return this._data.getCompressedWorker();var c=this._decompressWorker();return this._dataBinary||(c=c.pipe(new f.Utf8EncodeWorker)),g.createWorkerFrom(c,a,b)},_decompressWorker:function(){return this._data instanceof g?this._data.getContentWorker():this._data instanceof h?this._data:new e(this._data)}};for(var j=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],k=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},l=0;l<j.length;l++)i.prototype[j[l]]=k;b.exports=i},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(a,b,c){a("../modules/web.immediate"),b.exports=a("../modules/_core").setImmediate},{"../modules/_core":40,"../modules/web.immediate":56}],37:[function(a,b,c){b.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},{}],38:[function(a,b,c){var d=a("./_is-object");b.exports=function(a){if(!d(a))throw TypeError(a+" is not an object!");return a}},{"./_is-object":51}],39:[function(a,b,c){var d={}.toString;b.exports=function(a){return d.call(a).slice(8,-1)}},{}],40:[function(a,b,c){var d=b.exports={version:"2.3.0"};"number"==typeof __e&&(__e=d)},{}],41:[function(a,b,c){var d=a("./_a-function");b.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},{"./_a-function":37}],42:[function(a,b,c){b.exports=!a("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":45}],43:[function(a,b,c){var d=a("./_is-object"),e=a("./_global").document,f=d(e)&&d(e.createElement);b.exports=function(a){return f?e.createElement(a):{}}},{"./_global":46,"./_is-object":51}],44:[function(a,b,c){var d=a("./_global"),e=a("./_core"),f=a("./_ctx"),g=a("./_hide"),h="prototype",i=function(a,b,c){var j,k,l,m=a&i.F,n=a&i.G,o=a&i.S,p=a&i.P,q=a&i.B,r=a&i.W,s=n?e:e[b]||(e[b]={}),t=s[h],u=n?d:o?d[b]:(d[b]||{})[h];n&&(c=b);for(j in c)k=!m&&u&&void 0!==u[j],k&&j in s||(l=k?u[j]:c[j],s[j]=n&&"function"!=typeof u[j]?c[j]:q&&k?f(l,d):r&&u[j]==l?function(a){var b=function(b,c,d){if(this instanceof a){switch(arguments.length){case 0:return new a;case 1:return new a(b);case 2:return new a(b,c)}return new a(b,c,d)}return a.apply(this,arguments)};return b[h]=a[h],b}(l):p&&"function"==typeof l?f(Function.call,l):l,p&&((s.virtual||(s.virtual={}))[j]=l,a&i.R&&t&&!t[j]&&g(t,j,l)))};i.F=1,i.G=2,i.S=4,i.P=8,i.B=16,i.W=32,i.U=64,i.R=128,b.exports=i},{"./_core":40,"./_ctx":41,"./_global":46,"./_hide":47}],45:[function(a,b,c){b.exports=function(a){try{return!!a()}catch(b){return!0}}},{}],46:[function(a,b,c){var d=b.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=d)},{}],47:[function(a,b,c){var d=a("./_object-dp"),e=a("./_property-desc");b.exports=a("./_descriptors")?function(a,b,c){return d.f(a,b,e(1,c))}:function(a,b,c){return a[b]=c,a}},{"./_descriptors":42,"./_object-dp":52,"./_property-desc":53}],48:[function(a,b,c){b.exports=a("./_global").document&&document.documentElement},{"./_global":46}],49:[function(a,b,c){b.exports=!a("./_descriptors")&&!a("./_fails")(function(){return 7!=Object.defineProperty(a("./_dom-create")("div"),"a",{get:function(){return 7}}).a})},{"./_descriptors":42,"./_dom-create":43,"./_fails":45}],50:[function(a,b,c){b.exports=function(a,b,c){var d=void 0===c;switch(b.length){case 0:return d?a():a.call(c);case 1:return d?a(b[0]):a.call(c,b[0]);case 2:return d?a(b[0],b[1]):a.call(c,b[0],b[1]);case 3:return d?a(b[0],b[1],b[2]):a.call(c,b[0],b[1],b[2]);case 4:return d?a(b[0],b[1],b[2],b[3]):a.call(c,b[0],b[1],b[2],b[3])}return a.apply(c,b)}},{}],51:[function(a,b,c){b.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},{}],52:[function(a,b,c){var d=a("./_an-object"),e=a("./_ie8-dom-define"),f=a("./_to-primitive"),g=Object.defineProperty;c.f=a("./_descriptors")?Object.defineProperty:function(a,b,c){if(d(a),b=f(b,!0),d(c),e)try{return g(a,b,c)}catch(h){}if("get"in c||"set"in c)throw TypeError("Accessors not supported!");return"value"in c&&(a[b]=c.value),a}},{"./_an-object":38,"./_descriptors":42,"./_ie8-dom-define":49,"./_to-primitive":55}],53:[function(a,b,c){b.exports=function(a,b){return{enumerable:!(1&a),configurable:!(2&a),writable:!(4&a),value:b}}},{}],54:[function(a,b,c){var d,e,f,g=a("./_ctx"),h=a("./_invoke"),i=a("./_html"),j=a("./_dom-create"),k=a("./_global"),l=k.process,m=k.setImmediate,n=k.clearImmediate,o=k.MessageChannel,p=0,q={},r="onreadystatechange",s=function(){var a=+this;if(q.hasOwnProperty(a)){var b=q[a];delete q[a],b()}},t=function(a){s.call(a.data)};m&&n||(m=function(a){for(var b=[],c=1;arguments.length>c;)b.push(arguments[c++]);return q[++p]=function(){h("function"==typeof a?a:Function(a),b)},d(p),p},n=function(a){delete q[a]},"process"==a("./_cof")(l)?d=function(a){l.nextTick(g(s,a,1))}:o?(e=new o,f=e.port2,e.port1.onmessage=t,d=g(f.postMessage,f,1)):k.addEventListener&&"function"==typeof postMessage&&!k.importScripts?(d=function(a){k.postMessage(a+"","*")},k.addEventListener("message",t,!1)):d=r in j("script")?function(a){i.appendChild(j("script"))[r]=function(){i.removeChild(this),s.call(a)}}:function(a){setTimeout(g(s,a,1),0)}),b.exports={set:m,clear:n}},{"./_cof":39,"./_ctx":41,"./_dom-create":43,"./_global":46,"./_html":48,"./_invoke":50}],55:[function(a,b,c){var d=a("./_is-object");b.exports=function(a,b){if(!d(a))return a;var c,e;if(b&&"function"==typeof(c=a.toString)&&!d(e=c.call(a)))return e;if("function"==typeof(c=a.valueOf)&&!d(e=c.call(a)))return e;if(!b&&"function"==typeof(c=a.toString)&&!d(e=c.call(a)))return e;throw TypeError("Can't convert object to primitive value")}},{"./_is-object":51}],56:[function(a,b,c){var d=a("./_export"),e=a("./_task");d(d.G+d.B,{setImmediate:e.set,clearImmediate:e.clear})},{"./_export":44,"./_task":54}],57:[function(a,b,c){(function(a){"use strict";function c(){k=!0;for(var a,b,c=l.length;c;){for(b=l,l=[],a=-1;++a<c;)b[a]();c=l.length}k=!1}function d(a){1!==l.push(a)||k||e()}var e,f=a.MutationObserver||a.WebKitMutationObserver;if(f){var g=0,h=new f(c),i=a.document.createTextNode("");h.observe(i,{characterData:!0}),e=function(){i.data=g=++g%2}}else if(a.setImmediate||"undefined"==typeof a.MessageChannel)e="document"in a&&"onreadystatechange"in a.document.createElement("script")?function(){var b=a.document.createElement("script");b.onreadystatechange=function(){c(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},a.document.documentElement.appendChild(b)}:function(){setTimeout(c,0)};else{var j=new a.MessageChannel;j.port1.onmessage=c,e=function(){j.port2.postMessage(0)}}var k,l=[];b.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],58:[function(a,b,c){"use strict";function d(){}function e(a){if("function"!=typeof a)throw new TypeError("resolver must be a function");this.state=s,this.queue=[],this.outcome=void 0,a!==d&&i(this,a)}function f(a,b,c){this.promise=a,"function"==typeof b&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),"function"==typeof c&&(this.onRejected=c,this.callRejected=this.otherCallRejected)}function g(a,b,c){o(function(){var d;try{d=b(c)}catch(e){return p.reject(a,e)}d===a?p.reject(a,new TypeError("Cannot resolve promise with itself")):p.resolve(a,d)})}function h(a){var b=a&&a.then;if(a&&("object"==typeof a||"function"==typeof a)&&"function"==typeof b)return function(){b.apply(a,arguments)}}function i(a,b){function c(b){f||(f=!0,p.reject(a,b))}function d(b){f||(f=!0,p.resolve(a,b))}function e(){b(d,c)}var f=!1,g=j(e);"error"===g.status&&c(g.value)}function j(a,b){var c={};try{c.value=a(b),c.status="success"}catch(d){c.status="error",c.value=d}return c}function k(a){return a instanceof this?a:p.resolve(new this(d),a)}function l(a){var b=new this(d);return p.reject(b,a)}function m(a){function b(a,b){function d(a){g[b]=a,++h!==e||f||(f=!0,p.resolve(j,g))}c.resolve(a).then(d,function(a){f||(f=!0,p.reject(j,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=new Array(e),h=0,i=-1,j=new this(d);++i<e;)b(a[i],i);return j}function n(a){function b(a){c.resolve(a).then(function(a){f||(f=!0,p.resolve(h,a))},function(a){f||(f=!0,p.reject(h,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=-1,h=new this(d);++g<e;)b(a[g]);return h}var o=a("immediate"),p={},q=["REJECTED"],r=["FULFILLED"],s=["PENDING"];b.exports=e,e.prototype["catch"]=function(a){return this.then(null,a)},e.prototype.then=function(a,b){if("function"!=typeof a&&this.state===r||"function"!=typeof b&&this.state===q)return this;var c=new this.constructor(d);if(this.state!==s){var e=this.state===r?a:b;g(c,e,this.outcome)}else this.queue.push(new f(c,a,b));return c},f.prototype.callFulfilled=function(a){p.resolve(this.promise,a)},f.prototype.otherCallFulfilled=function(a){g(this.promise,this.onFulfilled,a)},f.prototype.callRejected=function(a){p.reject(this.promise,a)},f.prototype.otherCallRejected=function(a){g(this.promise,this.onRejected,a)},p.resolve=function(a,b){var c=j(h,b);if("error"===c.status)return p.reject(a,c.value);var d=c.value;if(d)i(a,d);else{a.state=r,a.outcome=b;for(var e=-1,f=a.queue.length;++e<f;)a.queue[e].callFulfilled(b)}return a},p.reject=function(a,b){a.state=q,a.outcome=b;for(var c=-1,d=a.queue.length;++c<d;)a.queue[c].callRejected(b);return a},e.resolve=k,e.reject=l,e.all=m,e.race=n},{immediate:57}],59:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":60,"./lib/inflate":61,"./lib/utils/common":62,"./lib/zlib/constants":65}],60:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);if(b.header&&h.deflateSetHeader(this.strm,b.header),b.dictionary){var e;if(e="string"==typeof b.dictionary?j.string2buf(b.dictionary):"[object ArrayBuffer]"===m.call(b.dictionary)?new Uint8Array(b.dictionary):b.dictionary,c=h.deflateSetDictionary(this.strm,e),c!==p)throw new Error(k[c]);this._dict_set=!0}}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg||k[c.err];return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d!==r||(this.onEnd(p),e.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":62,"./utils/strings":63,"./zlib/deflate":67,"./zlib/messages":72,"./zlib/zstream":74}],61:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg||k[c.err];return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l,m=this.strm,o=this.options.chunkSize,p=this.options.dictionary,q=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?m.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?m.input=new Uint8Array(a):m.input=a,m.next_in=0,m.avail_in=m.input.length;do{if(0===m.avail_out&&(m.output=new h.Buf8(o),m.next_out=0,m.avail_out=o),c=g.inflate(m,j.Z_NO_FLUSH),c===j.Z_NEED_DICT&&p&&(l="string"==typeof p?i.string2buf(p):"[object ArrayBuffer]"===n.call(p)?new Uint8Array(p):p,c=g.inflateSetDictionary(this.strm,l)),c===j.Z_BUF_ERROR&&q===!0&&(c=j.Z_OK,q=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;m.next_out&&(0!==m.avail_out&&c!==j.Z_STREAM_END&&(0!==m.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(m.output,m.next_out),f=m.next_out-e,k=i.buf2string(m.output,e),m.next_out=f,m.avail_out=o-f,f&&h.arraySet(m.output,m.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(m.output,m.next_out)))),0===m.avail_in&&0===m.avail_out&&(q=!0)}while((m.avail_in>0||0===m.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d!==j.Z_SYNC_FLUSH||(this.onEnd(j.Z_OK),m.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":62,"./utils/strings":63,"./zlib/constants":65,"./zlib/gzheader":68,"./zlib/inflate":70,"./zlib/messages":72,"./zlib/zstream":74}],62:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;b<c;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;b<c;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],63:[function(a,b,c){"use strict";function d(a,b){if(b<65537&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;d<b;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;j<256;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;f<h;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=c<128?1:c<2048?2:c<65536?3:4;for(b=new e.Buf8(i),g=0,f=0;g<i;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),c<128?b[g++]=c:c<2048?(b[g++]=192|c>>>6,b[g++]=128|63&c):c<65536?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;c<d;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;c<h;)if(f=a[c++],f<128)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&c<h;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:f<65536?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return c<0?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":62}],64:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0;
}b.exports=d},{}],65:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],66:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;c<256;c++){a=c;for(var d=0;d<8;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;h<g;h++)a=a>>>8^e[255&(a^b[h])];return a^-1}var f=d();b.exports=e},{}],67:[function(a,b,c){"use strict";function d(a,b){return a.msg=I[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(E.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){F._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,E.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=G(a.adler,b,e,c):2===a.state.wrap&&(a.adler=H(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-la?a.strstart-(a.w_size-la):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ka,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&f<m);if(d=ka-(m-f),f=m-ka,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-la)){E.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ja)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ja-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ja)););}while(a.lookahead<la&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===J)return ua;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ua;if(a.strstart-a.block_start>=a.w_size-la&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ua:ua}function o(a,b){for(var c,d;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c)),a.match_length>=ja)if(d=F._tr_tally(a,a.strstart-a.match_start,a.match_length-ja),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ja){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function p(a,b){for(var c,d,e;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ja-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===U||a.match_length===ja&&a.strstart-a.match_start>4096)&&(a.match_length=ja-1)),a.prev_length>=ja&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ja,d=F._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ja),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ja-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ua}else if(a.match_available){if(d=F._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ua}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=F._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ka){if(m(a),a.lookahead<=ka&&b===J)return ua;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ja&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ka;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&e<f);a.match_length=ka-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ja?(c=F._tr_tally(a,1,a.match_length-ja),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===J)return ua;break}if(a.match_length=0,c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=D[a.level].max_lazy,a.good_match=D[a.level].good_length,a.nice_match=D[a.level].nice_length,a.max_chain_length=D[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ja-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=$,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*ha),this.dyn_dtree=new E.Buf16(2*(2*fa+1)),this.bl_tree=new E.Buf16(2*(2*ga+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(ia+1),this.heap=new E.Buf16(2*ea+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*ea+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Z,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?na:sa,a.adler=2===b.wrap?0:1,b.last_flush=J,F._tr_init(b),O):d(a,Q)}function w(a){var b=v(a);return b===O&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?Q:(a.state.gzhead=b,O):Q}function y(a,b,c,e,f,g){if(!a)return Q;var h=1;if(b===T&&(b=6),e<0?(h=0,e=-e):e>15&&(h=2,e-=16),f<1||f>_||c!==$||e<8||e>15||b<0||b>9||g<0||g>X)return d(a,Q);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ja-1)/ja),i.window=new E.Buf8(2*i.w_size),i.head=new E.Buf16(i.hash_size),i.prev=new E.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new E.Buf8(i.pending_buf_size),i.d_buf=1*i.lit_bufsize,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,$,aa,ba,Y)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>N||b<0)return a?d(a,Q):Q;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ta&&b!==M)return d(a,0===a.avail_out?S:Q);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===na)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=H(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=oa):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,ya),h.status=sa);else{var m=$+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=V||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ma),m+=31-m%31,h.status=sa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===oa)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=qa)}else h.status=qa;if(h.status===qa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=ra)}else h.status=ra;if(h.status===ra&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=sa)):h.status=sa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,O}else if(0===a.avail_in&&e(b)<=e(c)&&b!==M)return d(a,S);if(h.status===ta&&0!==a.avail_in)return d(a,S);if(0!==a.avail_in||0!==h.lookahead||b!==J&&h.status!==ta){var o=h.strategy===V?r(h,b):h.strategy===W?q(h,b):D[h.level].func(h,b);if(o!==wa&&o!==xa||(h.status=ta),o===ua||o===wa)return 0===a.avail_out&&(h.last_flush=-1),O;if(o===va&&(b===K?F._tr_align(h):b!==N&&(F._tr_stored_block(h,0,0,!1),b===L&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,O}return b!==M?O:h.wrap<=0?P:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?O:P)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa&&b!==ta?d(a,Q):(a.state=null,b===sa?d(a,R):O)):Q}function C(a,b){var c,d,e,g,h,i,j,k,l=b.length;if(!a||!a.state)return Q;if(c=a.state,g=c.wrap,2===g||1===g&&c.status!==na||c.lookahead)return Q;for(1===g&&(a.adler=G(a.adler,b,l,0)),c.wrap=0,l>=c.w_size&&(0===g&&(f(c.head),c.strstart=0,c.block_start=0,c.insert=0),k=new E.Buf8(c.w_size),E.arraySet(k,b,l-c.w_size,c.w_size,0),b=k,l=c.w_size),h=a.avail_in,i=a.next_in,j=a.input,a.avail_in=l,a.next_in=0,a.input=b,m(c);c.lookahead>=ja;){d=c.strstart,e=c.lookahead-(ja-1);do c.ins_h=(c.ins_h<<c.hash_shift^c.window[d+ja-1])&c.hash_mask,c.prev[d&c.w_mask]=c.head[c.ins_h],c.head[c.ins_h]=d,d++;while(--e);c.strstart=d,c.lookahead=ja-1,m(c)}return c.strstart+=c.lookahead,c.block_start=c.strstart,c.insert=c.lookahead,c.lookahead=0,c.match_length=c.prev_length=ja-1,c.match_available=0,a.next_in=i,a.input=j,a.avail_in=h,c.wrap=g,O}var D,E=a("../utils/common"),F=a("./trees"),G=a("./adler32"),H=a("./crc32"),I=a("./messages"),J=0,K=1,L=3,M=4,N=5,O=0,P=1,Q=-2,R=-3,S=-5,T=-1,U=1,V=2,W=3,X=4,Y=0,Z=2,$=8,_=9,aa=15,ba=8,ca=29,da=256,ea=da+1+ca,fa=30,ga=19,ha=2*ea+1,ia=15,ja=3,ka=258,la=ka+ja+1,ma=32,na=42,oa=69,pa=73,qa=91,ra=103,sa=113,ta=666,ua=1,va=2,wa=3,xa=4,ya=3;D=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateSetDictionary=C,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":62,"./adler32":64,"./crc32":66,"./messages":72,"./trees":73}],68:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],69:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(q<w&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,q<w&&(p+=B[f++]<<q,q+=8,q<w&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(n<w){if(z+=l+n-w,w-=n,w<x){x-=w;do C[h++]=o[z++];while(--w);if(z=0,n<x){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(f<g&&h<j);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=f<g?5+(g-f):5-(f-g),a.avail_out=h<j?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],70:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=L,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new s.Buf32(pa),b.distcode=b.distdyn=new s.Buf32(qa),b.sane=1,b.back=-1,D):G}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):G}function h(a,b){var c,d;return a&&a.state?(d=a.state,b<0?(c=0,b=-b):(c=(b>>4)+1,b<48&&(b&=15)),b&&(b<8||b>15)?G:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):G}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==D&&(a.state=null),c):G}function j(a){return i(a,sa)}function k(a){if(ta){var b;for(q=new s.Buf32(512),r=new s.Buf32(32),b=0;b<144;)a.lens[b++]=8;for(;b<256;)a.lens[b++]=9;for(;b<280;)a.lens[b++]=7;for(;b<288;)a.lens[b++]=8;for(w(y,a.lens,0,288,q,0,a.work,{bits:9}),b=0;b<32;)a.lens[b++]=5;w(z,a.lens,0,32,r,0,a.work,{bits:5}),ta=!1}a.lencode=q,a.lenbits=9,a.distcode=r,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new s.Buf8(f.wsize)),d>=f.wsize?(s.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),s.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(s.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,r,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new s.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return G;c=a.state,c.mode===W&&(c.mode=X),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=D;a:for(;;)switch(c.mode){case L:if(0===c.wrap){c.mode=X;break}for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0),m=0,n=0,c.mode=M;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=ma;break}if((15&m)!==K){a.msg="unknown compression method",c.mode=ma;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=ma;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?U:W,m=0,n=0;break;case M:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==K){a.msg="unknown compression method",c.mode=ma;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=ma;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=N;case N:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=u(c.check,Ba,4,0)),m=0,n=0,c.mode=O;case O:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=P;case P:if(1024&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=Q;case Q:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),s.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=R;case R:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=S;case S:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=T;case T:if(512&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=ma;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=W;break;case U:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=V;case V:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,F;a.adler=c.check=1,c.mode=W;case W:if(b===B||b===C)break a;case X:if(c.last){m>>>=7&n,n-=7&n,c.mode=ja;break}for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=Y;break;case 1:if(k(c),c.mode=ca,b===C){m>>>=2,n-=2;break a}break;case 2:c.mode=_;break;case 3:a.msg="invalid block type",c.mode=ma}m>>>=2,n-=2;break;case Y:for(m>>>=7&n,n-=7&n;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=ma;break}if(c.length=65535&m,m=0,n=0,c.mode=Z,b===C)break a;case Z:c.mode=$;case $:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;s.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=W;break;case _:for(;n<14;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=ma;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.ncode;){for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=w(x,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=ma;break}c.have=0,c.mode=ba;case ba:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(sa<16)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=ma;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=ma;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===ma)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=ma;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=w(y,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=ma;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=w(z,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=ma;break}if(c.mode=ca,b===C)break a;case ca:c.mode=da;case da:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,v(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===W&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ia;break}if(32&ra){c.back=-1,c.mode=W;break}if(64&ra){a.msg="invalid literal/length code",c.mode=ma;break}c.extra=15&ra,c.mode=ea;case ea:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=fa;case fa:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=ma;break}c.offset=sa,c.extra=15&ra,c.mode=ga;case ga:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=ma;break}c.mode=ha;case ha:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=ma;break}q>c.wnext?(q-=c.wnext,r=c.wsize-q):r=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,r=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[r++];while(--q);0===c.length&&(c.mode=da);break;case ia:if(0===j)break a;f[h++]=c.length,j--,c.mode=da;break;case ja:if(c.wrap){for(;n<32;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?u(c.check,f,p,h-p):t(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=ma;break}m=0,n=0}c.mode=ka;case ka:if(c.wrap&&c.flags){for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=ma;break}m=0,n=0}c.mode=la;case la:xa=E;break a;case ma:xa=H;break a;case na:return I;case oa:default:return G}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<ma&&(c.mode<ja||b!==A))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=na,I):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?u(c.check,f,p,a.next_out-p):t(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===W?128:0)+(c.mode===ca||c.mode===Z?256:0),(0===o&&0===p||b===A)&&xa===D&&(xa=J),xa)}function n(a){if(!a||!a.state)return G;var b=a.state;return b.window&&(b.window=null),a.state=null,D}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?G:(c.head=b,b.done=!1,D)):G}function p(a,b){var c,d,e,f=b.length;return a&&a.state?(c=a.state,0!==c.wrap&&c.mode!==V?G:c.mode===V&&(d=1,d=t(d,b,f,0),d!==c.check)?H:(e=l(a,b,f,f))?(c.mode=na,I):(c.havedict=1,D)):G}var q,r,s=a("../utils/common"),t=a("./adler32"),u=a("./crc32"),v=a("./inffast"),w=a("./inftrees"),x=0,y=1,z=2,A=4,B=5,C=6,D=0,E=1,F=2,G=-2,H=-3,I=-4,J=-5,K=8,L=1,M=2,N=3,O=4,P=5,Q=6,R=7,S=8,T=9,U=10,V=11,W=12,X=13,Y=14,Z=15,$=16,_=17,aa=18,ba=19,ca=20,da=21,ea=22,fa=23,ga=24,ha=25,ia=26,ja=27,ka=28,la=29,ma=30,na=31,oa=32,pa=852,qa=592,ra=15,sa=ra,ta=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateSetDictionary=p,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":62,"./adler32":64,"./crc32":66,"./inffast":69,"./inftrees":71}],71:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;D<=e;D++)P[D]=0;for(E=0;E<o;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;F<G&&0===P[F];F++);for(H<F&&(H=F),K=1,D=1;D<=e;D++)if(K<<=1,K-=P[D],K<0)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;D<e;D++)Q[D+1]=Q[D]+P[D];for(E=0;E<o;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(;;){z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;I+J<G&&(K-=P[I+J],!(K<=0));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":62}],72:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],73:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return a<256?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;f<=W;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,
c=a.heap_max+1;c<V;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;d<=W;d++)f[d]=g=g+c[d-1]<<1;for(e=0;e<=b;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;d<Q-1;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;d<16;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;d<T;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;b<=W;b++)g[b]=0;for(a=0;a<=143;)ga[2*a+1]=8,a++,g[8]++;for(;a<=255;)ga[2*a+1]=9,a++,g[9]++;for(;a<=279;)ga[2*a+1]=7,a++,g[7]++;for(;a<=287;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;a<T;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;b<S;b++)a.dyn_ltree[2*b]=0;for(b=0;b<T;b++)a.dyn_dtree[2*b]=0;for(b=0;b<U;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;c<i;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=j<2?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;d<=c;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(h<j?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):h<=10?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;d<=c;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(h<l){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):h<=10?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;e<d;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;b<=31;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;b<R;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,f<=e&&(e=f)):e=f=c+5,c+4<=e&&b!==-1?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":62}],74:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[10])(10)}); | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/libs/zip.min.js | zip.min.js |
(function () {
'use strict';
var isCommonjs = typeof module !== 'undefined' && module.exports;
var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;
var fn = (function () {
var val;
var valLength;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// new WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// old WebKit (Safari 5.1)
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0, valLength = val.length; i < valLength; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
})();
var screenfull = {
request: function (elem) {
var request = fn.requestFullscreen;
elem = elem || document.documentElement;
// Work around Safari 5.1 bug: reports support for
// keyboard in fullscreen even though it doesn't.
// Browser sniffing, since the alternative with
// setTimeout is even worse.
if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) {
elem[request]();
} else {
elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
}
},
exit: function () {
document[fn.exitFullscreen]();
},
toggle: function (elem) {
if (this.isFullscreen) {
this.exit();
} else {
this.request(elem);
}
},
raw: fn
};
if (!fn) {
if (isCommonjs) {
module.exports = false;
} else {
window.screenfull = false;
}
return;
}
Object.defineProperties(screenfull, {
isFullscreen: {
get: function () {
return !!document[fn.fullscreenElement];
}
},
element: {
enumerable: true,
get: function () {
return document[fn.fullscreenElement];
}
},
enabled: {
enumerable: true,
get: function () {
// Coerce to boolean in case of old WebKit
return !!document[fn.fullscreenEnabled];
}
}
});
if (isCommonjs) {
module.exports = screenfull;
} else {
window.screenfull = screenfull;
}
})(); | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/libs/screenfull.js | screenfull.js |
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.localforage=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){(function(a){"use strict";function c(){k=!0;for(var a,b,c=l.length;c;){for(b=l,l=[],a=-1;++a<c;)b[a]();c=l.length}k=!1}function d(a){1!==l.push(a)||k||e()}var e,f=a.MutationObserver||a.WebKitMutationObserver;if(f){var g=0,h=new f(c),i=a.document.createTextNode("");h.observe(i,{characterData:!0}),e=function(){i.data=g=++g%2}}else if(a.setImmediate||"undefined"==typeof a.MessageChannel)e="document"in a&&"onreadystatechange"in a.document.createElement("script")?function(){var b=a.document.createElement("script");b.onreadystatechange=function(){c(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},a.document.documentElement.appendChild(b)}:function(){setTimeout(c,0)};else{var j=new a.MessageChannel;j.port1.onmessage=c,e=function(){j.port2.postMessage(0)}}var k,l=[];b.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],2:[function(a,b,c){"use strict";function d(){}function e(a){if("function"!=typeof a)throw new TypeError("resolver must be a function");this.state=s,this.queue=[],this.outcome=void 0,a!==d&&i(this,a)}function f(a,b,c){this.promise=a,"function"==typeof b&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),"function"==typeof c&&(this.onRejected=c,this.callRejected=this.otherCallRejected)}function g(a,b,c){o(function(){var d;try{d=b(c)}catch(b){return p.reject(a,b)}d===a?p.reject(a,new TypeError("Cannot resolve promise with itself")):p.resolve(a,d)})}function h(a){var b=a&&a.then;if(a&&"object"==typeof a&&"function"==typeof b)return function(){b.apply(a,arguments)}}function i(a,b){function c(b){f||(f=!0,p.reject(a,b))}function d(b){f||(f=!0,p.resolve(a,b))}function e(){b(d,c)}var f=!1,g=j(e);"error"===g.status&&c(g.value)}function j(a,b){var c={};try{c.value=a(b),c.status="success"}catch(a){c.status="error",c.value=a}return c}function k(a){return a instanceof this?a:p.resolve(new this(d),a)}function l(a){var b=new this(d);return p.reject(b,a)}function m(a){function b(a,b){function d(a){g[b]=a,++h!==e||f||(f=!0,p.resolve(j,g))}c.resolve(a).then(d,function(a){f||(f=!0,p.reject(j,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=new Array(e),h=0,i=-1,j=new this(d);++i<e;)b(a[i],i);return j}function n(a){function b(a){c.resolve(a).then(function(a){f||(f=!0,p.resolve(h,a))},function(a){f||(f=!0,p.reject(h,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=-1,h=new this(d);++g<e;)b(a[g]);return h}var o=a(1),p={},q=["REJECTED"],r=["FULFILLED"],s=["PENDING"];b.exports=c=e,e.prototype.catch=function(a){return this.then(null,a)},e.prototype.then=function(a,b){if("function"!=typeof a&&this.state===r||"function"!=typeof b&&this.state===q)return this;var c=new this.constructor(d);if(this.state!==s){var e=this.state===r?a:b;g(c,e,this.outcome)}else this.queue.push(new f(c,a,b));return c},f.prototype.callFulfilled=function(a){p.resolve(this.promise,a)},f.prototype.otherCallFulfilled=function(a){g(this.promise,this.onFulfilled,a)},f.prototype.callRejected=function(a){p.reject(this.promise,a)},f.prototype.otherCallRejected=function(a){g(this.promise,this.onRejected,a)},p.resolve=function(a,b){var c=j(h,b);if("error"===c.status)return p.reject(a,c.value);var d=c.value;if(d)i(a,d);else{a.state=r,a.outcome=b;for(var e=-1,f=a.queue.length;++e<f;)a.queue[e].callFulfilled(b)}return a},p.reject=function(a,b){a.state=q,a.outcome=b;for(var c=-1,d=a.queue.length;++c<d;)a.queue[c].callRejected(b);return a},c.resolve=k,c.reject=l,c.all=m,c.race=n},{1:1}],3:[function(a,b,c){(function(b){"use strict";"function"!=typeof b.Promise&&(b.Promise=a(2))}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{2:2}],4:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function e(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(a){}}function f(){try{if(!ga)return!1;var a="undefined"!=typeof openDatabase&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),b="function"==typeof fetch&&fetch.toString().indexOf("[native code")!==-1;return(!a||b)&&"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(a){return!1}}function g(){return"function"==typeof openDatabase}function h(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&localStorage.setItem}catch(a){return!1}}function i(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(f){if("TypeError"!==f.name)throw f;for(var c="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder,d=new c,e=0;e<a.length;e+=1)d.append(a[e]);return d.getBlob(b.type)}}function j(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function k(a,b,c){"function"==typeof b&&a.then(b),"function"==typeof c&&a.catch(c)}function l(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;e<b;e++)d[e]=a.charCodeAt(e);return c}function m(a){return new ja(function(b){var c=a.transaction(ka,"readwrite"),d=i([""]);c.objectStore(ka).put(d,"key"),c.onabort=function(a){a.preventDefault(),a.stopPropagation(),b(!1)},c.oncomplete=function(){var a=navigator.userAgent.match(/Chrome\/(\d+)/),c=navigator.userAgent.match(/Edge\//);b(c||!a||parseInt(a[1],10)>=43)}}).catch(function(){return!1})}function n(a){return"boolean"==typeof ha?ja.resolve(ha):m(a).then(function(a){return ha=a})}function o(a){var b=ia[a.name],c={};c.promise=new ja(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function p(a){var b=ia[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function q(a,b){return new ja(function(c,d){if(a.db){if(!b)return c(a.db);o(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=ga.open.apply(ga,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ka)}catch(c){if("ConstraintError"!==c.name)throw c;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(a){a.preventDefault(),d(f.error)},f.onsuccess=function(){c(f.result),p(a)}})}function r(a){return q(a,!1)}function s(a){return q(a,!0)}function t(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function u(a){return new ja(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function v(a){var b=l(atob(a.data));return i([b],{type:a.type})}function w(a){return a&&a.__local_forage_encoded_blob}function x(a){var b=this,c=b._initReady().then(function(){var a=ia[b._dbInfo.name];if(a&&a.dbReady)return a.dbReady});return k(c,a,a),c}function y(a){function b(){return ja.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ia||(ia={});var f=ia[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},ia[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=x);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady().catch(b))}var j=f.forages.slice(0);return ja.all(g).then(function(){return d.db=f.db,r(d)}).then(function(a){return d.db=a,t(d,c._defaultConfig.version)?s(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<j.length;b++){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function z(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),w(a)&&(a=v(a)),b(a)},g.onerror=function(){d(g.error)}}).catch(d)});return j(d,b),d}function A(a,b){var c=this,d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;w(d)&&(d=v(d));var e=a(d,c.key,h++);void 0!==e?b(e):c.continue()}else b()},g.onerror=function(){d(g.error)}}).catch(d)});return j(d,b),d}function B(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ja(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,"[object Blob]"===la.call(b)?n(f.db).then(function(a){return a?b:u(b)}):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName),h=g.put(b,a);null===b&&(b=void 0),d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}}).catch(e)});return j(e,c),e}function C(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g.delete(a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}}).catch(d)});return j(d,b),d}function D(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}}).catch(c)});return j(c,a),c}function E(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}}).catch(c)});return j(c,a),c}function F(a,b){var c=this,d=new ja(function(b,d){return a<0?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}}).catch(d)});return j(d,b),d}function G(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b.continue()):void a(g)},f.onerror=function(){c(f.error)}}).catch(c)});return j(c,a),c}function H(a){var b,c,d,e,f,g=.75*a.length,h=a.length,i=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var j=new ArrayBuffer(g),k=new Uint8Array(j);for(b=0;b<h;b+=4)c=na.indexOf(a[b]),d=na.indexOf(a[b+1]),e=na.indexOf(a[b+2]),f=na.indexOf(a[b+3]),k[i++]=c<<2|d>>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function I(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=na[c[b]>>2],d+=na[(3&c[b])<<4|c[b+1]>>4],d+=na[(15&c[b+1])<<2|c[b+2]>>6],d+=na[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function J(a,b){var c="";if(a&&(c=Ea.call(a)),a&&("[object ArrayBuffer]"===c||a.buffer&&"[object ArrayBuffer]"===Ea.call(a.buffer))){var d,e=qa;a instanceof ArrayBuffer?(d=a,e+=sa):(d=a.buffer,"[object Int8Array]"===c?e+=ua:"[object Uint8Array]"===c?e+=va:"[object Uint8ClampedArray]"===c?e+=wa:"[object Int16Array]"===c?e+=xa:"[object Uint16Array]"===c?e+=za:"[object Int32Array]"===c?e+=ya:"[object Uint32Array]"===c?e+=Aa:"[object Float32Array]"===c?e+=Ba:"[object Float64Array]"===c?e+=Ca:b(new Error("Failed to get type for BinaryArray"))),b(e+I(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=oa+a.type+"~"+I(this.result);b(qa+ta+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(c){console.error("Couldn't convert value into a JSON string: ",a),b(null,c)}}function K(a){if(a.substring(0,ra)!==qa)return JSON.parse(a);var b,c=a.substring(Da),d=a.substring(ra,Da);if(d===ta&&pa.test(c)){var e=c.match(pa);b=e[1],c=c.substring(e[0].length)}var f=H(c);switch(d){case sa:return f;case ta:return i([f],{type:b});case ua:return new Int8Array(f);case va:return new Uint8Array(f);case wa:return new Uint8ClampedArray(f);case xa:return new Int16Array(f);case za:return new Uint16Array(f);case ya:return new Int32Array(f);case Aa:return new Uint32Array(f);case Ba:return new Float32Array(f);case Ca:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function L(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ja(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(a){return d(a)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Fa,e}function M(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function N(a,b){var c=this,d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;h<g;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function O(a,b,c,d){var e=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var f=new ja(function(f,g){e.ready().then(function(){void 0===b&&(b=null);var h=b,i=e._dbInfo;i.serializer.serialize(b,function(b,j){j?g(j):i.db.transaction(function(c){c.executeSql("INSERT OR REPLACE INTO "+i.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){f(h)},function(a,b){g(b)})},function(b){if(b.code===b.QUOTA_ERR){if(d>0)return void f(O.apply(e,[a,h,c,d-1]));g(b)}})})}).catch(g)});return j(f,c),f}function P(a,b,c){return O.apply(this,[a,b,c,1])}function Q(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function R(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function S(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function T(a,b){var c=this,d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function U(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function V(a){var b=this,c={};if(a)for(var d in a)c[d]=a[d];return c.keyPrefix=c.name+"/",c.storeName!==b._defaultConfig.storeName&&(c.keyPrefix+=c.storeName+"/"),b._dbInfo=c,c.serializer=Fa,ja.resolve()}function W(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=localStorage.length-1;c>=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function X(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function Y(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;h<f;h++){var i=localStorage.key(h);if(0===i.indexOf(d)){var j=localStorage.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return j(d,b),d}function Z(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=localStorage.key(a)}catch(a){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return j(d,b),d}function $(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=localStorage.length,d=[],e=0;e<c;e++)0===localStorage.key(e).indexOf(a.keyPrefix)&&d.push(localStorage.key(e).substring(a.keyPrefix.length));return d});return j(c,a),c}function _(a){var b=this,c=b.keys().then(function(a){return a.length});return j(c,a),c}function aa(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;localStorage.removeItem(b.keyPrefix+a)});return j(d,b),d}function ba(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new ja(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{localStorage.setItem(g.keyPrefix+a,b),e(c)}catch(a){"QuotaExceededError"!==a.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==a.name||f(a),f(a)}})})});return j(e,c),e}function ca(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function da(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(Oa(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function ea(a){for(var b in Ja)if(Ja.hasOwnProperty(b)&&Ja[b]===a)return!0;return!1}var fa="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},ga=e();"undefined"==typeof Promise&&a(3);var ha,ia,ja=Promise,ka="local-forage-detect-blob-support",la=Object.prototype.toString,ma={_driver:"asyncStorage",_initStorage:y,iterate:A,getItem:z,setItem:B,removeItem:C,clear:D,length:E,key:F,keys:G},na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oa="~~local_forage_type~",pa=/^~~local_forage_type~([^~]+)~/,qa="__lfsc__:",ra=qa.length,sa="arbf",ta="blob",ua="si08",va="ui08",wa="uic8",xa="si16",ya="si32",za="ur16",Aa="ui32",Ba="fl32",Ca="fl64",Da=ra+sa.length,Ea=Object.prototype.toString,Fa={serialize:J,deserialize:K,stringToBuffer:H,bufferToString:I},Ga={_driver:"webSQLStorage",_initStorage:L,iterate:N,getItem:M,setItem:P,removeItem:Q,clear:R,length:S,key:T,keys:U},Ha={_driver:"localStorageWrapper",_initStorage:V,iterate:Y,getItem:X,setItem:ba,removeItem:aa,clear:W,length:_,key:Z,keys:$},Ia={},Ja={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},Ka=[Ja.INDEXEDDB,Ja.WEBSQL,Ja.LOCALSTORAGE],La=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],Ma={description:"",driver:Ka.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},Na={};Na[Ja.INDEXEDDB]=f(),Na[Ja.WEBSQL]=g(),Na[Ja.LOCALSTORAGE]=h();var Oa=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},Pa=function(){function a(b){d(this,a),this.INDEXEDDB=Ja.INDEXEDDB,this.LOCALSTORAGE=Ja.LOCALSTORAGE,this.WEBSQL=Ja.WEBSQL,this._defaultConfig=da({},Ma),this._config=da({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return a.prototype.config=function(a){if("object"===("undefined"==typeof a?"undefined":fa(a))){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a){if("storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),"version"===b&&"number"!=typeof a[b])return new Error("Database version must be a number.");this._config[b]=a[b]}return!("driver"in a&&a.driver)||this.setDriver(this._config.driver)}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new ja(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),f=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(ea(a._driver))return void c(f);for(var g=La.concat("_initStorage"),h=0;h<g.length;h++){var i=g[h];if(!i||!a[i]||"function"!=typeof a[i])return void c(e)}var j=ja.resolve(!0);"_support"in a&&(j=a._support&&"function"==typeof a._support?a._support():ja.resolve(!!a._support)),j.then(function(c){Na[d]=c,Ia[d]=a,b()},c)}catch(a){c(a)}});return k(d,b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,c){var d=this,e=ja.resolve().then(function(){if(!ea(a)){if(Ia[a])return Ia[a];throw new Error("Driver not found.")}switch(a){case d.INDEXEDDB:return ma;case d.LOCALSTORAGE:return Ha;case d.WEBSQL:return Ga}});return k(e,b,c),e},a.prototype.getSerializer=function(a){var b=ja.resolve(Fa);return k(b,a),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return k(c,a,a),c},a.prototype.setDriver=function(a,b,c){function d(){g._config.driver=g.driver()}function e(a){return g._extend(a),d(),g._ready=g._initStorage(g._config),g._ready}function f(a){return function(){function b(){for(;c<a.length;){var f=a[c];return c++,g._dbInfo=null,g._ready=null,g.getDriver(f).then(e).catch(b)}d();var h=new Error("No available storage method found.");return g._driverSet=ja.reject(h),g._driverSet}var c=0;return b()}}var g=this;Oa(a)||(a=[a]);var h=this._getSupportedDrivers(a),i=null!==this._driverSet?this._driverSet.catch(function(){return ja.resolve()}):ja.resolve();return this._driverSet=i.then(function(){var a=h[0];return g._dbInfo=null,g._ready=null,g.getDriver(a).then(function(a){g._driver=a._driver,d(),g._wrapLibraryMethodsWithReady(),g._initDriver=f(h)})}).catch(function(){d();var a=new Error("No available storage method found.");return g._driverSet=ja.reject(a),g._driverSet}),k(this._driverSet,b,c),this._driverSet},a.prototype.supports=function(a){return!!Na[a]},a.prototype._extend=function(a){da(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<La.length;a++)ca(this,La[a])},a.prototype.createInstance=function(b){return new a(b)},a}(),Qa=new Pa;b.exports=Qa},{3:3}]},{},[4])(4)}); | yuehui-jinshu | /yuehui_jinshu-2022.10.11.0-py3-none-any.whl/YuehuiJinshu/js/libs/localforage.min.js | localforage.min.js |
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):b(a.RSVP=a.RSVP||{})}(this,function(a){"use strict";function b(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function c(a){var b=a._promiseCallbacks;return b||(b=a._promiseCallbacks={}),b}function d(a,b){if(2!==arguments.length)return wa[a];wa[a]=b}function e(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function f(a){return"function"==typeof a}function g(a){return null!==a&&"object"==typeof a}function h(a){return null!==a&&"object"==typeof a}function i(){setTimeout(function(){for(var a=0;a<Aa.length;a++){var b=Aa[a],c=b.payload;c.guid=c.key+c.id,c.childGuid=c.key+c.childId,c.error&&(c.stack=c.error.stack),wa.trigger(b.name,b.payload)}Aa.length=0},50)}function j(a,b,c){1===Aa.push({name:a,payload:{key:b._guidKey,id:b._id,eventName:a,detail:b._result,childId:c&&c._id,label:b._label,timeStamp:za(),error:wa["instrument-with-stack"]?new Error(b._label):null}})&&i()}function k(a,b){var c=this;if(a&&"object"==typeof a&&a.constructor===c)return a;var d=new c(m,b);return s(d,a),d}function l(){return new TypeError("A promises callback cannot return that same promise.")}function m(){}function n(a){try{return a.then}catch(a){return Ea.error=a,Ea}}function o(a,b,c,d){try{a.call(b,c,d)}catch(a){return a}}function p(a,b,c){wa.async(function(a){var d=!1,e=o(c,b,function(c){d||(d=!0,b!==c?s(a,c,void 0):u(a,c))},function(b){d||(d=!0,v(a,b))},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,v(a,e))},a)}function q(a,b){b._state===Ca?u(a,b._result):b._state===Da?(b._onError=null,v(a,b._result)):w(b,void 0,function(c){b!==c?s(a,c,void 0):u(a,c)},function(b){return v(a,b)})}function r(a,b,c){b.constructor===a.constructor&&c===C&&a.constructor.resolve===k?q(a,b):c===Ea?(v(a,Ea.error),Ea.error=null):f(c)?p(a,b,c):u(a,b)}function s(a,b){a===b?u(a,b):e(b)?r(a,b,n(b)):u(a,b)}function t(a){a._onError&&a._onError(a._result),x(a)}function u(a,b){a._state===Ba&&(a._result=b,a._state=Ca,0===a._subscribers.length?wa.instrument&&j("fulfilled",a):wa.async(x,a))}function v(a,b){a._state===Ba&&(a._state=Da,a._result=b,wa.async(t,a))}function w(a,b,c,d){var e=a._subscribers,f=e.length;a._onError=null,e[f]=b,e[f+Ca]=c,e[f+Da]=d,0===f&&a._state&&wa.async(x,a)}function x(a){var b=a._subscribers,c=a._state;if(wa.instrument&&j(c===Ca?"fulfilled":"rejected",a),0!==b.length){for(var d=void 0,e=void 0,f=a._result,g=0;g<b.length;g+=3)d=b[g],e=b[g+c],d?A(c,d,e,f):e(f);a._subscribers.length=0}}function y(){this.error=null}function z(a,b){try{return a(b)}catch(a){return Fa.error=a,Fa}}function A(a,b,c,d){var e=f(c),g=void 0,h=void 0;if(e){if((g=z(c,d))===Fa)h=g.error,g.error=null;else if(g===b)return void v(b,l())}else g=d;b._state!==Ba||(e&&void 0===h?s(b,g):void 0!==h?v(b,h):a===Ca?u(b,g):a===Da&&v(b,g))}function B(a,b){var c=!1;try{b(function(b){c||(c=!0,s(a,b))},function(b){c||(c=!0,v(a,b))})}catch(b){v(a,b)}}function C(a,b,c){var d=this,e=d._state;if(e===Ca&&!a||e===Da&&!b)return wa.instrument&&j("chained",d,d),d;d._onError=null;var f=new d.constructor(m,c),g=d._result;if(wa.instrument&&j("chained",d,f),e===Ba)w(d,f,a,b);else{var h=e===Ca?a:b;wa.async(function(){return A(e,f,h,g)})}return f}function D(a,b,c){return a===Ca?{state:"fulfilled",value:c}:{state:"rejected",reason:c}}function E(a,b){return ya(a)?new Ga(this,a,!0,b).promise:this.reject(new TypeError("Promise.all must be called with an array"),b)}function F(a,b){var c=this,d=new c(m,b);if(!ya(a))return v(d,new TypeError("Promise.race must be called with an array")),d;for(var e=0;d._state===Ba&&e<a.length;e++)w(c.resolve(a[e]),void 0,function(a){return s(d,a)},function(a){return v(d,a)});return d}function G(a,b){var c=this,d=new c(m,b);return v(d,a),d}function H(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function I(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function J(){this.value=void 0}function K(a){try{return a.then}catch(a){return Ka.value=a,Ka}}function L(a,b,c){try{a.apply(b,c)}catch(a){return Ka.value=a,Ka}}function M(a,b){for(var c={},d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=a[f];for(var g=0;g<b.length;g++){c[b[g]]=e[g+1]}return c}function N(a){for(var b=a.length,c=new Array(b-1),d=1;d<b;d++)c[d-1]=a[d];return c}function O(a,b){return{then:function(c,d){return a.call(b,c,d)}}}function P(a,b){var c=function(){for(var c=this,d=arguments.length,e=new Array(d+1),f=!1,g=0;g<d;++g){var h=arguments[g];if(!f){if((f=S(h))===La){var i=new Ja(m);return v(i,La.value),i}f&&!0!==f&&(h=O(f,h))}e[g]=h}var j=new Ja(m);return e[d]=function(a,c){a?v(j,a):void 0===b?s(j,c):!0===b?s(j,N(arguments)):ya(b)?s(j,M(arguments,b)):s(j,c)},f?R(j,e,a,c):Q(j,e,a,c)};return c.__proto__=a,c}function Q(a,b,c,d){var e=L(c,d,b);return e===Ka&&v(a,e.value),a}function R(a,b,c,d){return Ja.all(b).then(function(b){var e=L(c,d,b);return e===Ka&&v(a,e.value),a})}function S(a){return!(!a||"object"!=typeof a)&&(a.constructor===Ja||K(a))}function T(a,b){return Ja.all(a,b)}function U(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function V(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function W(a,b){return ya(a)?new Ma(Ja,a,b).promise:Ja.reject(new TypeError("Promise.allSettled must be called with an array"),b)}function X(a,b){return Ja.race(a,b)}function Y(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function Z(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function $(a,b){return g(a)?new Oa(Ja,a,b).promise:Ja.reject(new TypeError("Promise.hash must be called with an object"),b)}function _(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function aa(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function ba(a,b){return g(a)?new Pa(Ja,a,!1,b).promise:Ja.reject(new TypeError("RSVP.hashSettled must be called with an object"),b)}function ca(a){throw setTimeout(function(){throw a}),a}function da(a){var b={resolve:void 0,reject:void 0};return b.promise=new Ja(function(a,c){b.resolve=a,b.reject=c},a),b}function ea(a,b,c){return ya(a)?f(b)?Ja.all(a,c).then(function(a){for(var d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=b(a[f]);return Ja.all(e,c)}):Ja.reject(new TypeError("RSVP.map expects a function as a second argument"),c):Ja.reject(new TypeError("RSVP.map must be called with an array"),c)}function fa(a,b){return Ja.resolve(a,b)}function ga(a,b){return Ja.reject(a,b)}function ha(a,b){return Ja.all(a,b)}function ia(a,b){return Ja.resolve(a,b).then(function(a){return ha(a,b)})}function ja(a,b,c){return ya(a)||g(a)&&void 0!==a.then?f(b)?(ya(a)?ha(a,c):ia(a,c)).then(function(a){for(var d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=b(a[f]);return ha(e,c).then(function(b){for(var c=new Array(d),e=0,f=0;f<d;f++)b[f]&&(c[e]=a[f],e++);return c.length=e,c})}):Ja.reject(new TypeError("RSVP.filter expects function as a second argument"),c):Ja.reject(new TypeError("RSVP.filter must be called with an array or promise"),c)}function ka(a,b){Xa[Qa]=a,Xa[Qa+1]=b,2===(Qa+=2)&&Ya()}function la(){var a=process.nextTick,b=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);return Array.isArray(b)&&"0"===b[1]&&"10"===b[2]&&(a=setImmediate),function(){return a(qa)}}function ma(){return void 0!==Ra?function(){Ra(qa)}:pa()}function na(){var a=0,b=new Ua(qa),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){return c.data=a=++a%2}}function oa(){var a=new MessageChannel;return a.port1.onmessage=qa,function(){return a.port2.postMessage(0)}}function pa(){return function(){return setTimeout(qa,1)}}function qa(){for(var a=0;a<Qa;a+=2){(0,Xa[a])(Xa[a+1]),Xa[a]=void 0,Xa[a+1]=void 0}Qa=0}function ra(){try{var a=require,b=a("vertx");return Ra=b.runOnLoop||b.runOnContext,ma()}catch(a){return pa()}}function sa(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function ta(){wa.on.apply(wa,arguments)}function ua(){wa.off.apply(wa,arguments)}var va={mixin:function(a){return a.on=this.on,a.off=this.off,a.trigger=this.trigger,a._promiseCallbacks=void 0,a},on:function(a,d){if("function"!=typeof d)throw new TypeError("Callback must be a function");var e=c(this),f=void 0;f=e[a],f||(f=e[a]=[]),-1===b(f,d)&&f.push(d)},off:function(a,d){var e=c(this),f=void 0,g=void 0;if(!d)return void(e[a]=[]);f=e[a],-1!==(g=b(f,d))&&f.splice(g,1)},trigger:function(a,b,d){var e=c(this),f=void 0;if(f=e[a])for(var g=0;g<f.length;g++)(0,f[g])(b,d)}},wa={instrument:!1};va.mixin(wa);var xa=void 0;xa=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)};var ya=xa,za=Date.now||function(){return(new Date).getTime()},Aa=[],Ba=void 0,Ca=1,Da=2,Ea=new y,Fa=new y,Ga=function(){function a(a,b,c,d){this._instanceConstructor=a,this.promise=new a(m,d),this._abortOnReject=c,this._init.apply(this,arguments)}return a.prototype._init=function(a,b){var c=b.length||0;this.length=c,this._remaining=c,this._result=new Array(c),this._enumerate(b),0===this._remaining&&u(this.promise,this._result)},a.prototype._enumerate=function(a){for(var b=this.length,c=this.promise,d=0;c._state===Ba&&d<b;d++)this._eachEntry(a[d],d)},a.prototype._settleMaybeThenable=function(a,b){var c=this._instanceConstructor,d=c.resolve;if(d===k){var e=n(a);if(e===C&&a._state!==Ba)a._onError=null,this._settledAt(a._state,b,a._result);else if("function"!=typeof e)this._remaining--,this._result[b]=this._makeResult(Ca,b,a);else if(c===Ja){var f=new c(m);r(f,a,e),this._willSettleAt(f,b)}else this._willSettleAt(new c(function(b){return b(a)}),b)}else this._willSettleAt(d(a),b)},a.prototype._eachEntry=function(a,b){h(a)?this._settleMaybeThenable(a,b):(this._remaining--,this._result[b]=this._makeResult(Ca,b,a))},a.prototype._settledAt=function(a,b,c){var d=this.promise;d._state===Ba&&(this._abortOnReject&&a===Da?v(d,c):(this._remaining--,this._result[b]=this._makeResult(a,b,c),0===this._remaining&&u(d,this._result)))},a.prototype._makeResult=function(a,b,c){return c},a.prototype._willSettleAt=function(a,b){var c=this;w(a,void 0,function(a){return c._settledAt(Ca,b,a)},function(a){return c._settledAt(Da,b,a)})},a}(),Ha="rsvp_"+za()+"-",Ia=0,Ja=function(){function a(b,c){this._id=Ia++,this._label=c,this._state=void 0,this._result=void 0,this._subscribers=[],wa.instrument&&j("created",this),m!==b&&("function"!=typeof b&&H(),this instanceof a?B(this,b):I())}return a.prototype._onError=function(a){var b=this;wa.after(function(){b._onError&&wa.trigger("error",a,b._label)})},a.prototype.catch=function(a,b){return this.then(void 0,a,b)},a.prototype.finally=function(a,b){var c=this,d=c.constructor;return c.then(function(b){return d.resolve(a()).then(function(){return b})},function(b){return d.resolve(a()).then(function(){throw b})},b)},a}();Ja.cast=k,Ja.all=E,Ja.race=F,Ja.resolve=k,Ja.reject=G,Ja.prototype._guidKey=Ha,Ja.prototype.then=C;var Ka=new J,La=new J,Ma=function(a){function b(b,c,d){return U(this,a.call(this,b,c,!1,d))}return V(b,a),b}(Ga);Ma.prototype._makeResult=D;var Na=Object.prototype.hasOwnProperty,Oa=function(a){function b(b,c){var d=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],e=arguments[3];return Y(this,a.call(this,b,c,d,e))}return Z(b,a),b.prototype._init=function(a,b){this._result={},this._enumerate(b),0===this._remaining&&u(this.promise,this._result)},b.prototype._enumerate=function(a){var b=this.promise,c=[];for(var d in a)Na.call(a,d)&&c.push({position:d,entry:a[d]});var e=c.length;this._remaining=e;for(var f=void 0,g=0;b._state===Ba&&g<e;g++)f=c[g],this._eachEntry(f.entry,f.position)},b}(Ga),Pa=function(a){function b(b,c,d){return _(this,a.call(this,b,c,!1,d))}return aa(b,a),b}(Oa);Pa.prototype._makeResult=D;var Qa=0,Ra=void 0,Sa="undefined"!=typeof window?window:void 0,Ta=Sa||{},Ua=Ta.MutationObserver||Ta.WebKitMutationObserver,Va="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Wa="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,Xa=new Array(1e3),Ya=void 0;Ya=Va?la():Ua?na():Wa?oa():void 0===Sa&&"function"==typeof require?ra():pa();if("object"==typeof self)self;else{if("object"!=typeof global)throw new Error("no global: `self` or `global` found");global}var Za;wa.async=ka,wa.after=function(a){return setTimeout(a,0)};var $a=fa,_a=function(a,b){return wa.async(a,b)};if("undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var ab=window.__PROMISE_INSTRUMENTATION__;d("instrument",!0);for(var bb in ab)ab.hasOwnProperty(bb)&&ta(bb,ab[bb])}var cb=(Za={asap:ka,cast:$a,Promise:Ja,EventTarget:va,all:T,allSettled:W,race:X,hash:$,hashSettled:ba,rethrow:ca,defer:da,denodeify:P,configure:d,on:ta,off:ua,resolve:fa,reject:ga,map:ea},sa(Za,"async",_a),sa(Za,"filter",ja),Za);a.default=cb,a.asap=ka,a.cast=$a,a.Promise=Ja,a.EventTarget=va,a.all=T,a.allSettled=W,a.race=X,a.hash=$,a.hashSettled=ba,a.rethrow=ca,a.defer=da,a.denodeify=P,a.configure=d,a.on=ta,a.off=ua,a.resolve=fa,a.reject=ga,a.map=ea,a.async=_a,a.filter=ja,Object.defineProperty(a,"__esModule",{value:!0})});var EPUBJS=EPUBJS||{};EPUBJS.core={};var ELEMENT_NODE=1,TEXT_NODE=3,COMMENT_NODE=8,DOCUMENT_NODE=9;EPUBJS.core.getEl=function(a){return document.getElementById(a)},EPUBJS.core.getEls=function(a){return document.getElementsByClassName(a)},EPUBJS.core.request=function(a,b,c){var d,e=window.URL,f=e?"blob":"arraybuffer",g=new RSVP.defer,h=new XMLHttpRequest,i=XMLHttpRequest.prototype,j=function(){var a;this.readyState==this.DONE&&(200!==this.status&&0!==this.status||!this.response?g.reject({message:this.response,stack:(new Error).stack}):(a="xml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xml"):"xhtml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xhtml+xml"):"html"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"text/html"):"json"==b?JSON.parse(this.response):"blob"==b?e?this.response:new Blob([this.response]):this.response,g.resolve(a)))};return"overrideMimeType"in i||Object.defineProperty(i,"overrideMimeType",{value:function(a){}}),h.onreadystatechange=j,h.open("GET",a,!0),c&&(h.withCredentials=!0),b||(d=EPUBJS.core.uri(a),b=d.extension,b={htm:"html"}[b]||b),"blob"==b&&(h.responseType=f),"json"==b&&h.setRequestHeader("Accept","application/json"),"xml"==b&&(h.responseType="document",h.overrideMimeType("text/xml")),"xhtml"==b&&(h.responseType="document"),"html"==b&&(h.responseType="document"),"binary"==b&&(h.responseType="arraybuffer"),h.send(),g.promise},EPUBJS.core.toArray=function(a){var b=[];for(var c in a){var d;a.hasOwnProperty(c)&&(d=a[c],d.ident=c,b.push(d))}return b},EPUBJS.core.uri=function(a){var b,c,d,e={protocol:"",host:"",path:"",origin:"",directory:"",base:"",filename:"",extension:"",fragment:"",href:a},f=a.indexOf("blob:"),g=a.indexOf("://"),h=a.indexOf("?"),i=a.indexOf("#");return 0===f?(e.protocol="blob",e.base=a.indexOf(0,i),e):(-1!=i&&(e.fragment=a.slice(i+1),a=a.slice(0,i)),-1!=h&&(e.search=a.slice(h+1),a=a.slice(0,h),href=e.href),-1!=g?(e.protocol=a.slice(0,g),b=a.slice(g+3),d=b.indexOf("/"),-1===d?(e.host=e.path,e.path=""):(e.host=b.slice(0,d),e.path=b.slice(d)),e.origin=e.protocol+"://"+e.host,e.directory=EPUBJS.core.folder(e.path),e.base=e.origin+e.directory):(e.path=a,e.directory=EPUBJS.core.folder(a),e.base=e.directory),e.filename=a.replace(e.base,""),c=e.filename.lastIndexOf("."),-1!=c&&(e.extension=e.filename.slice(c+1)),e)},EPUBJS.core.folder=function(a){var b=a.lastIndexOf("/");if(-1==b);return a.slice(0,b+1)},EPUBJS.core.dataURLToBlob=function(a){var b,c,d,e,f,g=";base64,";if(-1==a.indexOf(g))return b=a.split(","),c=b[0].split(":")[1],d=b[1],new Blob([d],{type:c});b=a.split(g),c=b[0].split(":")[1],d=window.atob(b[1]),e=d.length,f=new Uint8Array(e);for(var h=0;h<e;++h)f[h]=d.charCodeAt(h);return new Blob([f],{type:c})},EPUBJS.core.addScript=function(a,b,c){var d,e;e=!1,d=document.createElement("script"),d.type="text/javascript",d.async=!1,d.src=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.addScripts=function(a,b,c){var d=a.length,e=0,f=function(){e++,d==e?b&&b():EPUBJS.core.addScript(a[e],f,c)};EPUBJS.core.addScript(a[e],f,c)},EPUBJS.core.addCss=function(a,b,c){var d,e;e=!1,d=document.createElement("link"),d.type="text/css",d.rel="stylesheet",d.href=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.prefixed=function(a){var b=["Webkit","Moz","O","ms"],c=a[0].toUpperCase()+a.slice(1),d=b.length;if(void 0!==document.documentElement.style[a])return a;for(var e=0;e<d;e++)if(void 0!==document.documentElement.style[b[e]+c])return b[e]+c;return a},EPUBJS.core.resolveUrl=function(a,b){var c,d,e=[],f=EPUBJS.core.uri(b),g=a.split("/");return f.host?b:(g.pop(),d=b.split("/"),d.forEach(function(a){".."===a?g.pop():e.push(a)}),c=g.concat(e),c.join("/"))},EPUBJS.core.uuid=function(){var a=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(b){var c=(a+16*Math.random())%16|0;return a=Math.floor(a/16),("x"==b?c:7&c|8).toString(16)})},EPUBJS.core.insert=function(a,b,c){var d=EPUBJS.core.locationOf(a,b,c);return b.splice(d,0,a),d},EPUBJS.core.locationOf=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:a<b?-1:(a=b)?0:void 0}),h-g<=0?i:(f=c(b[i],a),h-g==1?f>0?i:i+1:0===f?i:-1===f?EPUBJS.core.locationOf(a,b,c,i,h):EPUBJS.core.locationOf(a,b,c,g,i))},EPUBJS.core.indexOfSorted=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:a<b?-1:(a=b)?0:void 0}),h-g<=0?-1:(f=c(b[i],a),h-g==1?0===f?i:-1:0===f?i:-1===f?EPUBJS.core.indexOfSorted(a,b,c,i,h):EPUBJS.core.indexOfSorted(a,b,c,g,i))},EPUBJS.core.queue=function(a){var b=[],c=a,d=function(a,c,d){return b.push({funcName:a,args:c,context:d}),b},e=function(){var a;b.length&&(a=b.shift(),c[a.funcName].apply(a.context||c,a.args))};return{enqueue:d,dequeue:e,flush:function(){for(;b.length;)e()},clear:function(){b=[]},length:function(){return b.length}}},EPUBJS.core.getElementXPath=function(a){return a&&a.id?'//*[@id="'+a.id+'"]':EPUBJS.core.getElementTreeXPath(a)},EPUBJS.core.getElementTreeXPath=function(a){var b,c,d,e,f=[],g="http://www.w3.org/1999/xhtml"===a.ownerDocument.documentElement.getAttribute("xmlns");for(a.nodeType===Node.TEXT_NODE&&(b=EPUBJS.core.indexOfTextNode(a)+1,f.push("text()["+b+"]"),a=a.parentNode);a&&1==a.nodeType;a=a.parentNode){b=0;for(var h=a.previousSibling;h;h=h.previousSibling)h.nodeType!=Node.DOCUMENT_TYPE_NODE&&h.nodeName==a.nodeName&&++b;c=a.nodeName.toLowerCase(),d=g?"xhtml:"+c:c,e=b?"["+(b+1)+"]":"",f.splice(0,0,d+e)}return f.length?"./"+f.join("/"):null},EPUBJS.core.nsResolver=function(a){return{xhtml:"http://www.w3.org/1999/xhtml",epub:"http://www.idpf.org/2007/ops"}[a]||null},EPUBJS.core.cleanStringForXpath=function(a){var b=a.match(/[^'"]+|['"]/g);return b=b.map(function(a){return"'"===a?'"\'"':'"'===a?"'\"'":"'"+a+"'"}),"concat('',"+b.join(",")+")"},EPUBJS.core.indexOfTextNode=function(a){for(var b,c=a.parentNode,d=c.childNodes,e=-1,f=0;f<d.length&&(b=d[f],b.nodeType===Node.TEXT_NODE&&e++,b!=a);f++);return e},EPUBJS.core.defaults=function(a){for(var b=1,c=arguments.length;b<c;b++){var d=arguments[b];for(var e in d)void 0===a[e]&&(a[e]=d[e])}return a},EPUBJS.core.extend=function(a){return[].slice.call(arguments,1).forEach(function(b){b&&Object.getOwnPropertyNames(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))})}),a},EPUBJS.core.clone=function(a){return EPUBJS.core.isArray(a)?a.slice():EPUBJS.core.extend({},a)},EPUBJS.core.isElement=function(a){return!(!a||1!=a.nodeType)},EPUBJS.core.isNumber=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},EPUBJS.core.isString=function(a){return"string"==typeof a||a instanceof String},EPUBJS.core.isArray=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},EPUBJS.core.values=function(a){var b,c,d,e=-1;if(!a)return[];for(b=Object.keys(a),c=b.length,d=Array(c);++e<c;)d[e]=a[b[e]];return d},EPUBJS.core.indexOfNode=function(a,b){for(var c,d=a.parentNode,e=d.childNodes,f=-1,g=0;g<e.length&&(c=e[g],c.nodeType===b&&f++,c!=a);g++);return f},EPUBJS.core.indexOfTextNode=function(a){return EPUBJS.core.indexOfNode(a,TEXT_NODE)},EPUBJS.core.indexOfElementNode=function(a){return EPUBJS.core.indexOfNode(a,ELEMENT_NODE)};var EPUBJS=EPUBJS||{};EPUBJS.reader={},EPUBJS.reader.plugins={},function(a,b){var c=(a.ePubReader,a.ePubReader=function(a,b){return new EPUBJS.Reader(a,b)});"function"==typeof define&&define.amd?define(function(){return Reader}):"undefined"!=typeof module&&module.exports&&(module.exports=c)}(window,jQuery),EPUBJS.Reader=function(a,b){var c,d,e,f=this,g=$("#viewer"),h=window.location.search;this.settings=EPUBJS.core.defaults(b||{},{bookPath:a,restore:!1,reload:!1,bookmarks:void 0,annotations:void 0,contained:void 0,bookKey:void 0,styles:void 0,sidebarReflow:!1,generatePagination:!1,history:!0}),h&&(e=h.slice(1).split("&"),e.forEach(function(a){var b=a.split("="),c=b[0],d=b[1]||"";f.settings[c]=decodeURIComponent(d)})),this.setBookKey(this.settings.bookPath),this.settings.restore&&this.isSaved()&&this.applySavedSettings(),this.settings.styles=this.settings.styles||{fontSize:"100%"},this.book=c=new ePub(this.settings.bookPath,this.settings),this.offline=!1,this.sidebarOpen=!1,this.settings.bookmarks||(this.settings.bookmarks=[]),this.settings.annotations||(this.settings.annotations=[]),this.settings.generatePagination&&c.generatePagination(g.width(),g.height()),this.rendition=c.renderTo("viewer",{ignoreClass:"annotator-hl",width:"100%",height:"100%"}),this.settings.previousLocationCfi?this.displayed=this.rendition.display(this.settings.previousLocationCfi):this.displayed=this.rendition.display(),c.ready.then(function(){f.ReaderController=EPUBJS.reader.ReaderController.call(f,c),f.SettingsController=EPUBJS.reader.SettingsController.call(f,c),f.ControlsController=EPUBJS.reader.ControlsController.call(f,c),f.SidebarController=EPUBJS.reader.SidebarController.call(f,c),f.BookmarksController=EPUBJS.reader.BookmarksController.call(f,c),f.NotesController=EPUBJS.reader.NotesController.call(f,c),window.addEventListener("hashchange",this.hashChanged.bind(this),!1),document.addEventListener("keydown",this.adjustFontSize.bind(this),!1),this.rendition.on("keydown",this.adjustFontSize.bind(this)),this.rendition.on("keydown",f.ReaderController.arrowKeys.bind(this)),this.rendition.on("selected",this.selectedRange.bind(this))}.bind(this)).then(function(){f.ReaderController.hideLoader()}.bind(this));for(d in EPUBJS.reader.plugins)EPUBJS.reader.plugins.hasOwnProperty(d)&&(f[d]=EPUBJS.reader.plugins[d].call(f,c));return c.loaded.metadata.then(function(a){f.MetaController=EPUBJS.reader.MetaController.call(f,a)}),c.loaded.navigation.then(function(a){f.TocController=EPUBJS.reader.TocController.call(f,a)}),window.addEventListener("beforeunload",this.unload.bind(this),!1),this},EPUBJS.Reader.prototype.adjustFontSize=function(a){var b,c=2,d=a.ctrlKey||a.metaKey;this.settings.styles&&(this.settings.styles.fontSize||(this.settings.styles.fontSize="100%"),b=parseInt(this.settings.styles.fontSize.slice(0,-1)),d&&187==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize",b+c+"%")),d&&189==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize",b-c+"%")),d&&48==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize","100%")))},EPUBJS.Reader.prototype.addBookmark=function(a){this.isBookmarked(a)>-1||(this.settings.bookmarks.push(a),this.trigger("reader:bookmarked",a))},EPUBJS.Reader.prototype.removeBookmark=function(a){var b=this.isBookmarked(a);-1!==b&&(this.settings.bookmarks.splice(b,1),this.trigger("reader:unbookmarked",b))},EPUBJS.Reader.prototype.isBookmarked=function(a){return this.settings.bookmarks.indexOf(a)},EPUBJS.Reader.prototype.clearBookmarks=function(){this.settings.bookmarks=[]},EPUBJS.Reader.prototype.addNote=function(a){this.settings.annotations.push(a)},EPUBJS.Reader.prototype.removeNote=function(a){var b=this.settings.annotations.indexOf(a);-1!==b&&delete this.settings.annotations[b]},EPUBJS.Reader.prototype.clearNotes=function(){this.settings.annotations=[]},EPUBJS.Reader.prototype.setBookKey=function(a){return this.settings.bookKey||(this.settings.bookKey="epubjsreader:"+EPUBJS.VERSION+":"+window.location.host+":"+a),this.settings.bookKey},EPUBJS.Reader.prototype.isSaved=function(a){return!!localStorage&&null!==localStorage.getItem(this.settings.bookKey)},EPUBJS.Reader.prototype.removeSavedSettings=function(){if(!localStorage)return!1;localStorage.removeItem(this.settings.bookKey)},EPUBJS.Reader.prototype.applySavedSettings=function(){var a;if(!localStorage)return!1;try{a=JSON.parse(localStorage.getItem(this.settings.bookKey))}catch(a){return!1}return!!a&&(a.styles&&(this.settings.styles=EPUBJS.core.defaults(this.settings.styles||{},a.styles)),this.settings=EPUBJS.core.defaults(this.settings,a),!0)},EPUBJS.Reader.prototype.saveSettings=function(){if(this.book&&(this.settings.previousLocationCfi=this.rendition.currentLocation().start.cfi),!localStorage)return!1;localStorage.setItem(this.settings.bookKey,JSON.stringify(this.settings))},EPUBJS.Reader.prototype.unload=function(){this.settings.restore&&localStorage&&this.saveSettings()},EPUBJS.Reader.prototype.hashChanged=function(){var a=window.location.hash.slice(1);this.rendition.display(a)},EPUBJS.Reader.prototype.selectedRange=function(a){var b="#"+a;this.settings.history&&window.location.hash!=b&&(history.pushState({},"",b),this.currentLocationCfi=a)},RSVP.EventTarget.mixin(EPUBJS.Reader.prototype),EPUBJS.reader.BookmarksController=function(){var a=this.book,b=this.rendition,c=$("#bookmarksView"),d=c.find("#bookmarks"),e=document.createDocumentFragment(),f=function(){c.show()},g=function(){c.hide()},h=0,i=function(c){var d=document.createElement("li"),e=document.createElement("a");d.id="bookmark-"+h,d.classList.add("list_item");var f,g=a.spine.get(c);return g.index in a.navigation.toc?(f=a.navigation.toc[g.index],e.textContent=f.label):e.textContent=c,e.href=c,e.classList.add("bookmark_link"),e.addEventListener("click",function(a){var c=this.getAttribute("href");b.display(c),a.preventDefault()},!1),d.appendChild(e),h++,d};return this.settings.bookmarks.forEach(function(a){var b=i(a);e.appendChild(b)}),d.append(e),this.on("reader:bookmarked",function(a){var b=i(a);d.append(b)}),this.on("reader:unbookmarked",function(a){$("#bookmark-"+a).remove()}),{show:f,hide:g}},EPUBJS.reader.ControlsController=function(a){var b=this,c=this.rendition,d=($("#store"),$("#fullscreen")),e=($("#fullscreenicon"),$("#cancelfullscreenicon"),$("#slider")),f=($("#main"),$("#sidebar"),$("#setting")),g=$("#bookmark");return e.on("click",function(){b.sidebarOpen?(b.SidebarController.hide(),e.addClass("icon-menu"),e.removeClass("icon-right")):(b.SidebarController.show(),e.addClass("icon-right"),e.removeClass("icon-menu"))}),"undefined"!=typeof screenfull&&(d.on("click",function(){screenfull.toggle($("#container")[0])}),screenfull.raw&&document.addEventListener(screenfull.raw.fullscreenchange,function(){fullscreen=screenfull.isFullscreen,fullscreen?d.addClass("icon-resize-small").removeClass("icon-resize-full"):d.addClass("icon-resize-full").removeClass("icon-resize-small")})),f.on("click",function(){b.SettingsController.show()}),g.on("click",function(){var a=b.rendition.currentLocation().start.cfi;-1===b.isBookmarked(a)?(b.addBookmark(a),g.addClass("icon-bookmark").removeClass("icon-bookmark-empty")):(b.removeBookmark(a),g.removeClass("icon-bookmark").addClass("icon-bookmark-empty"))}),c.on("relocated",function(a){var c=a.start.cfi,d="#"+c;-1===b.isBookmarked(c)?g.removeClass("icon-bookmark").addClass("icon-bookmark-empty"):g.addClass("icon-bookmark").removeClass("icon-bookmark-empty"),b.currentLocationCfi=c,b.settings.history&&window.location.hash!=d&&history.pushState({},"",d)}),{}},EPUBJS.reader.MetaController=function(a){var b=a.title,c=a.creator,d=$("#book-title"),e=$("#chapter-title"),f=$("#title-seperator");document.title=b+" – "+c,d.html(b),e.html(c),f.show()},EPUBJS.reader.NotesController=function(){var a=this.book,b=this.rendition,c=this,d=$("#notesView"),e=$("#notes"),f=$("#note-text"),g=$("#note-anchor"),h=c.settings.annotations,i=a.renderer,j=[],k=new ePub.CFI,l=function(){d.show()},m=function(){d.hide()},n=function(d){var e,h,i,j,l,m=a.renderer.doc;if(m.caretPositionFromPoint?(e=m.caretPositionFromPoint(d.clientX,d.clientY),h=e.offsetNode,i=e.offset):m.caretRangeFromPoint&&(e=m.caretRangeFromPoint(d.clientX,d.clientY),h=e.startContainer,i=e.startOffset),3!==h.nodeType)for(var q=0;q<h.childNodes.length;q++)if(3==h.childNodes[q].nodeType){h=h.childNodes[q];break}i=h.textContent.indexOf(".",i),-1===i?i=h.length:i+=1,j=k.generateCfiFromTextNode(h,i,a.renderer.currentChapter.cfiBase),l={annotatedAt:new Date,anchor:j,body:f.val()},c.addNote(l),o(l),p(l),f.val(""),g.text("Attach"),f.prop("disabled",!1),b.off("click",n)},o=function(a){var c=document.createElement("li"),d=document.createElement("a");c.innerHTML=a.body,d.innerHTML=" context »",d.href="#"+a.anchor,d.onclick=function(){return b.display(a.anchor),!1},c.appendChild(d),e.append(c)},p=function(b){var c=a.renderer.doc,d=document.createElement("span"),e=document.createElement("a");d.classList.add("footnotesuperscript","reader_generated"),d.style.verticalAlign="super",d.style.fontSize=".75em",d.style.lineHeight="1em",e.style.padding="2px",e.style.backgroundColor="#fffa96",e.style.borderRadius="5px",e.style.cursor="pointer",d.id="note-"+EPUBJS.core.uuid(),e.innerHTML=h.indexOf(b)+1+"[Reader]",d.appendChild(e),k.addMarker(b.anchor,c,d),q(d,b.body)},q=function(a,d){var e=a.id,f=function(){var c,f,l,m,n=i.height,o=i.width,p=225;j[e]||(j[e]=document.createElement("div"),j[e].setAttribute("class","popup"),pop_content=document.createElement("div"),j[e].appendChild(pop_content),pop_content.innerHTML=d,pop_content.setAttribute("class","pop_content"),i.render.document.body.appendChild(j[e]),j[e].addEventListener("mouseover",g,!1),j[e].addEventListener("mouseout",h,!1),b.on("locationChanged",k,this),b.on("locationChanged",h,this)),c=j[e],f=a.getBoundingClientRect(),l=f.left,m=f.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=l-popRect.width/2+"px",c.style.top=m+"px",p>n/2.5&&(p=n/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+m>=n-25?(c.style.top=m-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),l-popRect.width<=0?(c.style.left=l+"px",c.classList.add("left")):c.classList.remove("left"),l+popRect.width/2>=o?(c.style.left=l-300+"px",popRect=c.getBoundingClientRect(),c.style.left=l-popRect.width+"px",popRect.height+m>=n-25?(c.style.top=m-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")},g=function(){j[e].classList.add("on")},h=function(){j[e].classList.remove("on")},k=function(){setTimeout(function(){j[e].classList.remove("show")},100)},m=function(){c.ReaderController.slideOut(),l()};a.addEventListener("mouseover",f,!1),a.addEventListener("mouseout",k,!1),a.addEventListener("click",m,!1)};return g.on("click",function(a){g.text("Cancel"),f.prop("disabled","true"),b.on("click",n)}),h.forEach(function(a){o(a)}),{show:l,hide:m}},EPUBJS.reader.ReaderController=function(a){var b=$("#main"),c=$("#divider"),d=$("#loader"),e=$("#next"),f=$("#prev"),g=this,a=this.book,h=this.rendition,i=function(){h.currentLocation().start.cfi;g.settings.sidebarReflow?(b.removeClass("single"),b.one("transitionend",function(){h.resize()})):b.removeClass("closed")},j=function(){var a=h.currentLocation();if(a){a.start.cfi;g.settings.sidebarReflow?(b.addClass("single"),b.one("transitionend",function(){h.resize()})):b.addClass("closed")}},k=function(){d.show(),n()},l=function(){d.hide()},m=function(){c.addClass("show")},n=function(){c.removeClass("show")},o=!1,p=function(b){37==b.keyCode&&("rtl"===a.package.metadata.direction?h.next():h.prev(),f.addClass("active"),o=!0,setTimeout(function(){o=!1,f.removeClass("active")},100),b.preventDefault()),39==b.keyCode&&("rtl"===a.package.metadata.direction?h.prev():h.next(),e.addClass("active"),o=!0,setTimeout(function(){o=!1,e.removeClass("active")},100),b.preventDefault())};return document.addEventListener("keydown",p,!1),e.on("click",function(b){"rtl"===a.package.metadata.direction?h.prev():h.next(),b.preventDefault()}),f.on("click",function(b){"rtl"===a.package.metadata.direction?h.next():h.prev(),b.preventDefault()}),h.on("layout",function(a){!0===a.spread?m():n()}),h.on("relocated",function(a){a.atStart&&f.addClass("disabled"),a.atEnd&&e.addClass("disabled")}),{slideOut:j,slideIn:i,showLoader:k,hideLoader:l,showDivider:m,hideDivider:n,arrowKeys:p}},EPUBJS.reader.SettingsController=function(){var a=(this.book,this),b=$("#settings-modal"),c=$(".overlay"),d=function(){b.addClass("md-show")},e=function(){b.removeClass("md-show")};return $("#sidebarReflow").on("click",function(){a.settings.sidebarReflow=!a.settings.sidebarReflow}),b.find(".closer").on("click",function(){e()}),c.on("click",function(){e()}),{show:d,hide:e}},EPUBJS.reader.SidebarController=function(a){var b=this,c=$("#sidebar"),d=$("#panels"),e="Toc",f=function(a){var c=a+"Controller";e!=a&&void 0!==b[c]&&(b[e+"Controller"].hide(),b[c].show(),e=a,d.find(".active").removeClass("active"),d.find("#show-"+a).addClass("active"))},g=function(){return e},h=function(){b.sidebarOpen=!0,b.ReaderController.slideOut(),c.addClass("open")},i=function(){b.sidebarOpen=!1,b.ReaderController.slideIn(),c.removeClass("open")};return d.find(".show_view").on("click",function(a){var b=$(this).data("view");f(b),a.preventDefault()}),{show:h,hide:i,getActivePanel:g,changePanelTo:f}},EPUBJS.reader.TocController=function(a){var b=(this.book,this.rendition),c=$("#tocView"),d=document.createDocumentFragment(),e=!1,f=function(a,b){var c=document.createElement("ul");return b||(b=1),a.forEach(function(a){var d=document.createElement("li"),e=document.createElement("a");toggle=document.createElement("a");var g;d.id="toc-"+a.id,d.classList.add("list_item"),e.textContent=a.label,e.href=a.href,e.classList.add("toc_link"),d.appendChild(e),a.subitems&&a.subitems.length>0&&(b++,g=f(a.subitems,b),toggle.classList.add("toc_toggle"),d.insertBefore(toggle,e),d.appendChild(g)),c.appendChild(d)}),c},g=function(){c.show()},h=function(){c.hide()},i=function(a){var b=a.id,d=c.find("#toc-"+b),f=c.find(".currentChapter");c.find(".openChapter");d.length&&(d!=f&&d.has(e).length>0&&f.removeClass("currentChapter"),d.addClass("currentChapter"),d.parents("li").addClass("openChapter"))};b.on("renderered",i);var j=f(a);return d.appendChild(j),c.append(d),c.find(".toc_link").on("click",function(a){var d=this.getAttribute("href");a.preventDefault(),b.display(d),c.find(".currentChapter").addClass("openChapter").removeClass("currentChapter"),$(this).parent("li").addClass("currentChapter")}),c.find(".toc_toggle").on("click",function(a){var b=$(this).parent("li"),c=b.hasClass("openChapter");a.preventDefault(),c?b.removeClass("openChapter"):b.addClass("openChapter")}),{show:g,hide:h}}; | yuehui-miji | /yuehui-miji-2022.10.11.0.tar.gz/yuehui-miji-2022.10.11.0/YuehuiMiji/js/reader.min.js | reader.min.js |
EPUBJS.Hooks.register("beforeChapterDisplay").endnotes=function(a,b){var c=b.contents.querySelectorAll("a[href]"),d=Array.prototype.slice.call(c),e=EPUBJS.core.folder(location.pathname),f=(EPUBJS.cssPath,{});EPUBJS.core.addCss(EPUBJS.cssPath+"popup.css",!1,b.render.document.head),d.forEach(function(a){function c(){var c,h,n=b.height,o=b.width,p=225;m||(c=j.cloneNode(!0),m=c.querySelector("p")),f[i]||(f[i]=document.createElement("div"),f[i].setAttribute("class","popup"),pop_content=document.createElement("div"),f[i].appendChild(pop_content),pop_content.appendChild(m),pop_content.setAttribute("class","pop_content"),b.render.document.body.appendChild(f[i]),f[i].addEventListener("mouseover",d,!1),f[i].addEventListener("mouseout",e,!1),b.on("renderer:pageChanged",g,this),b.on("renderer:pageChanged",e,this)),c=f[i],h=a.getBoundingClientRect(),k=h.left,l=h.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=k-popRect.width/2+"px",c.style.top=l+"px",p>n/2.5&&(p=n/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+l>=n-25?(c.style.top=l-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),k-popRect.width<=0?(c.style.left=k+"px",c.classList.add("left")):c.classList.remove("left"),k+popRect.width/2>=o?(c.style.left=k-300+"px",popRect=c.getBoundingClientRect(),c.style.left=k-popRect.width+"px",popRect.height+l>=n-25?(c.style.top=l-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")}function d(){f[i].classList.add("on")}function e(){f[i].classList.remove("on")}function g(){setTimeout(function(){f[i].classList.remove("show")},100)}var h,i,j,k,l,m;"noteref"==a.getAttribute("epub:type")&&(h=a.getAttribute("href"),i=h.replace("#",""),j=b.render.document.getElementById(i),a.addEventListener("mouseover",c,!1),a.addEventListener("mouseout",g,!1))}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").mathml=function(a,b){if(b.currentChapter.manifestProperties.indexOf("mathml")!==-1){b.render.iframe.contentWindow.mathmlCallback=a;var c=document.createElement("script");c.type="text/x-mathjax-config",c.innerHTML=' MathJax.Hub.Register.StartupHook("End",function () { window.mathmlCallback(); }); MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); ',b.doc.body.appendChild(c),EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",null,b.doc.head)}else a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").smartimages=function(a,b){var c=b.contents.querySelectorAll("img"),d=Array.prototype.slice.call(c),e=b.height;if("reflowable"!=b.layoutSettings.layout)return void a();d.forEach(function(a){var c=function(){var c,d=a.getBoundingClientRect(),f=d.height,g=d.top,h=a.getAttribute("data-height"),i=h||f,j=Number(getComputedStyle(a,"").fontSize.match(/(\d*(\.\d*)?)px/)[1]),k=j?j/2:0;e=b.contents.clientHeight,g<0&&(g=0),a.style.maxWidth="100%",i+g>=e?(g<e/2?(c=e-g-k,a.style.maxHeight=c+"px",a.style.width="auto"):(i>e&&(a.style.maxHeight=e+"px",a.style.width="auto",d=a.getBoundingClientRect(),i=d.height),a.style.display="block",a.style.WebkitColumnBreakBefore="always",a.style.breakBefore="column"),a.setAttribute("data-height",c)):(a.style.removeProperty("max-height"),a.style.removeProperty("margin-top"))},d=function(){b.off("renderer:resized",c),b.off("renderer:chapterUnload",this)};a.addEventListener("load",c,!1),b.on("renderer:resized",c),b.on("renderer:chapterUnload",d),c()}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").transculsions=function(a,b){var c=b.contents.querySelectorAll("[transclusion]");Array.prototype.slice.call(c).forEach(function(a){function c(){j=g,k=h,j>chapter.colWidth&&(d=chapter.colWidth/j,j=chapter.colWidth,k*=d),f.width=j,f.height=k}var d,e=a.getAttribute("ref"),f=document.createElement("iframe"),g=a.getAttribute("width"),h=a.getAttribute("height"),i=a.parentNode,j=g,k=h;c(),b.listenUntil("renderer:resized","renderer:chapterUnloaded",c),f.src=e,i.replaceChild(f,a)}),a&&a()}; | yuehui-miji | /yuehui-miji-2022.10.11.0.tar.gz/yuehui-miji-2022.10.11.0/YuehuiMiji/js/hooks.min.js | hooks.min.js |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.