Files
unshackle/unshackle/core/plugins.py
T

166 lines
7.2 KiB
Python

"""The DRM plugin registry: each DRM system that is not built into core comes from a plugin in ``directories.plugins``.
A plugin is a zip file or a folder that holds one Python package. Its ``__init__.py`` sets ``PLUGIN`` to a
:class:`DrmPlugin`. The registry loads the plugins on the first lookup, with the standard library only, and
never from a peer or a URL.
"""
from __future__ import annotations
import importlib.util
import logging
import re
import sys
import threading
import types
import zipimport
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
from importlib.resources.abc import Traversable
from uuid import UUID
from unshackle.core.drm.custom import CustomDRM
log = logging.getLogger("plugins")
PACKAGE = "unshackle_drm_plugins"
BUILT_IN = ("widevine", "playready", "clearkey", "clearkeycenc", "clearkeyctr")
ID = re.compile(r"[a-z][a-z0-9_]*")
@dataclass(frozen=True)
class DrmPlugin:
"""The facts and hooks of a DRM system that a plugin adds; core reads these in place of a class check.
``id`` names the system on the wire, in an export and in the CDM catalogue. ``licensing`` is "held" when
the DRM holds its content key from the start, or "local" when a plugin device licenses it. ``media`` "own" is a
cipher that is not CENC: no KID to probe and no fragment to check. ``mode`` "segment" decrypts each
segment as it lands, several at once, then calls ``finish`` on the merged file; "track" decrypts the merged file once.
``decrypt`` writes only its destination path, whatever its name.
``wire_data`` names the keys of ``CustomDRM.data`` that a peer and an export may carry: licence data, never a
server secret. ``kids`` reads the KIDs from that data before any licence, so a vault can answer first, and may
set the ``display_id`` of the DRM; ``licence`` runs at the licence step of a download with a device of this
plugin. ``finish`` returns False for a track that the cipher leaves clear: its merged file proves no content key,
so it gets no decode check.
The CDM that ``load_device`` builds may carry a ``device_name`` for the load log.
``devices`` gives the plugin's own folder of device files (``importlib.resources``, so a zip works too), searched
after the operator's device folders; a call per lookup keeps a zip plugin closed. ``default_device`` names the
device a service gets when its config names none of this system.
``version`` goes to a remote server with the id. ``device_facts`` names the device attributes a service may read
to pick streams; a remote client sends their values, never a path or a device file, so that a server whose session
the client's device licenses gives the service a stand-in with them.
"""
id: str
label: str
licensing: Literal["held", "local"]
media: Literal["cenc", "own"]
mode: Literal["segment", "track"]
decrypt: Callable[[CustomDRM, Path, Path], None]
wire_data: tuple[str, ...] = ()
device_suffix: str | None = None
load_device: Callable[[Traversable], Any] | None = None
devices: Callable[[], Traversable] | None = None
default_device: str | None = None
licence: Callable[[CustomDRM, Any], None] | None = None
kids: Callable[[CustomDRM], list[UUID]] | None = None
finish: Callable[[CustomDRM, Path, Any], bool] | None = None
version: str = ""
device_facts: tuple[str, ...] = ()
def __post_init__(self) -> None:
if not ID.fullmatch(self.id) or self.id in BUILT_IN:
raise ValueError(f"Bad DRM plugin id {self.id!r}")
if self.licensing not in ("held", "local") or self.media not in ("cenc", "own"):
raise ValueError(f"Bad licensing or media of DRM plugin {self.id!r}")
if self.mode not in ("segment", "track"):
raise ValueError(f"Bad mode of DRM plugin {self.id!r}")
if bool(self.device_suffix) != (self.load_device is not None):
raise ValueError(f"DRM plugin {self.id!r} needs both device_suffix and load_device, or neither")
if (self.devices is not None or self.default_device or self.device_facts) and not self.device_suffix:
raise ValueError(f"DRM plugin {self.id!r} has devices but no device_suffix")
PLUGINS: dict[str, DrmPlugin] | None = None
LOCK = threading.RLock()
def plugins() -> dict[str, DrmPlugin]:
"""Every loaded plugin by id; the first call loads the plugin folder."""
global PLUGINS
if PLUGINS is not None:
return PLUGINS
with LOCK:
if PLUGINS is None:
from unshackle.core.config import config
PLUGINS = {} # a plugin that looks up the registry while it loads finds it empty, not a deadlock
PLUGINS = load_folder(config.directories.plugins)
return PLUGINS
def get(plugin_id: Any) -> DrmPlugin | None:
"""The plugin with the id ``plugin_id``, or None."""
return plugins().get(plugin_id) if isinstance(plugin_id, str) else None
def load_folder(folder: Path) -> dict[str, DrmPlugin]:
"""The plugins in ``folder`` by id. A plugin that fails to load, or repeats an id, logs one warning."""
found: dict[str, DrmPlugin] = {}
if not folder.is_dir():
return found
for path in sorted(folder.iterdir()):
if not (path.suffix == ".zip" or (path / "__init__.py").is_file()):
continue
try:
plugin = load_plugin(path)
except (Exception, SystemExit) as e:
log.warning(f"DRM plugin {path.name} failed to load: {e!r}")
continue
if plugin.id in found:
log.warning(f"DRM plugin {path.name} repeats the id {plugin.id!r}, skipped")
continue
found[plugin.id] = plugin
return found
def load_plugin(path: Path) -> DrmPlugin:
"""Import the plugin package of the zip file or folder ``path`` and return its ``PLUGIN``.
The package imports as ``unshackle_drm_plugins.<stem>``, so it never shadows an installed package.
"""
name = f"{PACKAGE}.{path.stem}"
if not ID.fullmatch(path.stem):
raise ValueError(f"Bad plugin name {path.stem!r}")
if path.suffix == ".zip":
loader = zipimport.zipimporter(str(path))
spec = importlib.util.spec_from_loader(name, loader, origin=str(path), is_package=True)
if spec is not None:
spec.submodule_search_locations = [str(path / path.stem)]
else:
spec = importlib.util.spec_from_file_location(
name, path / "__init__.py", submodule_search_locations=[str(path)]
)
if spec is None or spec.loader is None:
raise ImportError(f"No package in {path.name}")
sys.modules.setdefault(PACKAGE, types.ModuleType(PACKAGE))
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
try:
spec.loader.exec_module(module)
plugin = getattr(module, "PLUGIN", None)
if not isinstance(plugin, DrmPlugin):
raise TypeError(f"{path.name} sets no PLUGIN of type DrmPlugin")
except BaseException:
for loaded in [key for key in sys.modules if key == name or key.startswith(name + ".")]:
del sys.modules[loaded]
raise
return plugin
__all__ = ("DrmPlugin", "get", "load_folder", "load_plugin", "plugins")