plugins.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 = 'yt_dlp_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 yt-dlp 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 yt-dlp config folders
  57. candidate_locations.extend(_get_package_paths(
  58. *get_user_config_dirs('yt-dlp'),
  59. *get_system_config_dirs('yt-dlp'),
  60. containing_folder='plugins'))
  61. # Load from yt-dlp-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='yt-dlp-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. try:
  74. if candidate.is_dir():
  75. yield candidate
  76. elif path.suffix in ('.zip', '.egg', '.whl') and path.is_file():
  77. if parts in dirs_in_zip(path):
  78. yield candidate
  79. except PermissionError as e:
  80. write_string(f'Permission error while accessing modules in "{e.filename}"\n')
  81. def find_spec(self, fullname, path=None, target=None):
  82. if fullname not in self.packages:
  83. return None
  84. search_locations = list(map(str, self.search_locations(fullname)))
  85. if not search_locations:
  86. return None
  87. spec = importlib.machinery.ModuleSpec(fullname, PluginLoader(), is_package=True)
  88. spec.submodule_search_locations = search_locations
  89. return spec
  90. def invalidate_caches(self):
  91. dirs_in_zip.cache_clear()
  92. for package in self.packages:
  93. if package in sys.modules:
  94. del sys.modules[package]
  95. def directories():
  96. spec = importlib.util.find_spec(PACKAGE_NAME)
  97. return spec.submodule_search_locations if spec else []
  98. def iter_modules(subpackage):
  99. fullname = f'{PACKAGE_NAME}.{subpackage}'
  100. with contextlib.suppress(ModuleNotFoundError):
  101. pkg = importlib.import_module(fullname)
  102. yield from pkgutil.iter_modules(path=pkg.__path__, prefix=f'{fullname}.')
  103. def load_module(module, module_name, suffix):
  104. return inspect.getmembers(module, lambda obj: (
  105. inspect.isclass(obj)
  106. and obj.__name__.endswith(suffix)
  107. and obj.__module__.startswith(module_name)
  108. and not obj.__name__.startswith('_')
  109. and obj.__name__ in getattr(module, '__all__', [obj.__name__])))
  110. def load_plugins(name, suffix):
  111. classes = {}
  112. for finder, module_name, _ in iter_modules(name):
  113. if any(x.startswith('_') for x in module_name.split('.')):
  114. continue
  115. try:
  116. if sys.version_info < (3, 10) and isinstance(finder, zipimport.zipimporter):
  117. # zipimporter.load_module() is deprecated in 3.10 and removed in 3.12
  118. # The exec_module branch below is the replacement for >= 3.10
  119. # See: https://docs.python.org/3/library/zipimport.html#zipimport.zipimporter.exec_module
  120. module = finder.load_module(module_name)
  121. else:
  122. spec = finder.find_spec(module_name)
  123. module = importlib.util.module_from_spec(spec)
  124. sys.modules[module_name] = module
  125. spec.loader.exec_module(module)
  126. except Exception:
  127. write_string(f'Error while importing module {module_name!r}\n{traceback.format_exc(limit=-1)}')
  128. continue
  129. classes.update(load_module(module, module_name, suffix))
  130. # Compat: old plugin system using __init__.py
  131. # Note: plugins imported this way do not show up in directories()
  132. # nor are considered part of the yt_dlp_plugins namespace package
  133. with contextlib.suppress(FileNotFoundError):
  134. spec = importlib.util.spec_from_file_location(
  135. name, Path(get_executable_path(), COMPAT_PACKAGE_NAME, name, '__init__.py'))
  136. plugins = importlib.util.module_from_spec(spec)
  137. sys.modules[spec.name] = plugins
  138. spec.loader.exec_module(plugins)
  139. classes.update(load_module(plugins, spec.name, suffix))
  140. return classes
  141. sys.meta_path.insert(0, PluginFinder(f'{PACKAGE_NAME}.extractor', f'{PACKAGE_NAME}.postprocessor'))
  142. __all__ = ['directories', 'load_plugins', 'PACKAGE_NAME', 'COMPAT_PACKAGE_NAME']