plugins.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import contextlib
  2. import importlib
  3. import importlib.abc
  4. import importlib.machinery
  5. import importlib.util
  6. import inspect
  7. import itertools
  8. import pkgutil
  9. import sys
  10. import traceback
  11. import zipimport
  12. from pathlib import Path
  13. from zipfile import ZipFile
  14. from .compat import functools # isort: split
  15. from .utils import (
  16. get_executable_path,
  17. get_system_config_dirs,
  18. get_user_config_dirs,
  19. orderedSet,
  20. write_string,
  21. )
  22. PACKAGE_NAME = 'hypervideo_dl_plugins'
  23. COMPAT_PACKAGE_NAME = 'ytdlp_plugins'
  24. class PluginLoader(importlib.abc.Loader):
  25. """Dummy loader for virtual namespace packages"""
  26. def exec_module(self, module):
  27. return None
  28. @functools.cache
  29. def dirs_in_zip(archive):
  30. try:
  31. with ZipFile(archive) as zip_:
  32. return set(itertools.chain.from_iterable(
  33. Path(file).parents for file in zip_.namelist()))
  34. except FileNotFoundError:
  35. pass
  36. except Exception as e:
  37. write_string(f'WARNING: Could not read zip file {archive}: {e}\n')
  38. return set()
  39. class PluginFinder(importlib.abc.MetaPathFinder):
  40. """
  41. This class provides one or multiple namespace packages.
  42. It searches in sys.path and hypervideo config folders for
  43. the existing subdirectories from which the modules can be imported
  44. """
  45. def __init__(self, *packages):
  46. self._zip_content_cache = {}
  47. self.packages = set(itertools.chain.from_iterable(
  48. itertools.accumulate(name.split('.'), lambda a, b: '.'.join((a, b)))
  49. for name in packages))
  50. def search_locations(self, fullname):
  51. candidate_locations = []
  52. def _get_package_paths(*root_paths, containing_folder='plugins'):
  53. for config_dir in orderedSet(map(Path, root_paths), lazy=True):
  54. with contextlib.suppress(OSError):
  55. yield from (config_dir / containing_folder).iterdir()
  56. # Load from hypervideo config folders
  57. candidate_locations.extend(_get_package_paths(
  58. *get_user_config_dirs('hypervideo'),
  59. *get_system_config_dirs('hypervideo'),
  60. containing_folder='plugins'))
  61. # Load from hypervideo-plugins folders
  62. candidate_locations.extend(_get_package_paths(
  63. get_executable_path(),
  64. *get_user_config_dirs(''),
  65. *get_system_config_dirs(''),
  66. containing_folder='hypervideo-plugins'))
  67. candidate_locations.extend(map(Path, sys.path)) # PYTHONPATH
  68. with contextlib.suppress(ValueError): # Added when running __main__.py directly
  69. candidate_locations.remove(Path(__file__).parent)
  70. parts = Path(*fullname.split('.'))
  71. for path in orderedSet(candidate_locations, lazy=True):
  72. candidate = path / parts
  73. if candidate.is_dir():
  74. yield candidate
  75. elif path.suffix in ('.zip', '.egg', '.whl') and path.is_file():
  76. if parts in dirs_in_zip(path):
  77. yield candidate
  78. def find_spec(self, fullname, path=None, target=None):
  79. if fullname not in self.packages:
  80. return None
  81. search_locations = list(map(str, self.search_locations(fullname)))
  82. if not search_locations:
  83. return None
  84. spec = importlib.machinery.ModuleSpec(fullname, PluginLoader(), is_package=True)
  85. spec.submodule_search_locations = search_locations
  86. return spec
  87. def invalidate_caches(self):
  88. dirs_in_zip.cache_clear()
  89. for package in self.packages:
  90. if package in sys.modules:
  91. del sys.modules[package]
  92. def directories():
  93. spec = importlib.util.find_spec(PACKAGE_NAME)
  94. return spec.submodule_search_locations if spec else []
  95. def iter_modules(subpackage):
  96. fullname = f'{PACKAGE_NAME}.{subpackage}'
  97. with contextlib.suppress(ModuleNotFoundError):
  98. pkg = importlib.import_module(fullname)
  99. yield from pkgutil.iter_modules(path=pkg.__path__, prefix=f'{fullname}.')
  100. def load_module(module, module_name, suffix):
  101. return inspect.getmembers(module, lambda obj: (
  102. inspect.isclass(obj)
  103. and obj.__name__.endswith(suffix)
  104. and obj.__module__.startswith(module_name)
  105. and not obj.__name__.startswith('_')
  106. and obj.__name__ in getattr(module, '__all__', [obj.__name__])))
  107. def load_plugins(name, suffix):
  108. classes = {}
  109. for finder, module_name, _ in iter_modules(name):
  110. if any(x.startswith('_') for x in module_name.split('.')):
  111. continue
  112. try:
  113. if sys.version_info < (3, 10) and isinstance(finder, zipimport.zipimporter):
  114. # zipimporter.load_module() is deprecated in 3.10 and removed in 3.12
  115. # The exec_module branch below is the replacement for >= 3.10
  116. # See: https://docs.python.org/3/library/zipimport.html#zipimport.zipimporter.exec_module
  117. module = finder.load_module(module_name)
  118. else:
  119. spec = finder.find_spec(module_name)
  120. module = importlib.util.module_from_spec(spec)
  121. sys.modules[module_name] = module
  122. spec.loader.exec_module(module)
  123. except Exception:
  124. write_string(f'Error while importing module {module_name!r}\n{traceback.format_exc(limit=-1)}')
  125. continue
  126. classes.update(load_module(module, module_name, suffix))
  127. # Compat: old plugin system using __init__.py
  128. # Note: plugins imported this way do not show up in directories()
  129. # nor are considered part of the hypervideo_dl_plugins namespace package
  130. with contextlib.suppress(FileNotFoundError):
  131. spec = importlib.util.spec_from_file_location(
  132. name, Path(get_executable_path(), COMPAT_PACKAGE_NAME, name, '__init__.py'))
  133. plugins = importlib.util.module_from_spec(spec)
  134. sys.modules[spec.name] = plugins
  135. spec.loader.exec_module(plugins)
  136. classes.update(load_module(plugins, spec.name, suffix))
  137. return classes
  138. sys.meta_path.insert(0, PluginFinder(f'{PACKAGE_NAME}.extractor', f'{PACKAGE_NAME}.postprocessor'))
  139. __all__ = ['directories', 'load_plugins', 'PACKAGE_NAME', 'COMPAT_PACKAGE_NAME']