codekingpro/portable-devtools
115k
1import re2import warnings3from collections.abc import Sequence4from dataclasses import dataclass5from dataclasses import fields6from dataclasses import is_dataclass7from typing import Any8from typing import ClassVar9from typing import TYPE_CHECKING10 11import mitmproxy.flow12 13if TYPE_CHECKING:14 import mitmproxy.addonmanager15 import mitmproxy.log16 17 18class Hook:19 name: ClassVar[str]20 21 def args(self) -> list[Any]:22 args = []23 for field in fields(self): # type: ignore[arg-type]24 args.append(getattr(self, field.name))25 return args26 27 def __new__(cls, *args, **kwargs):28 if cls is Hook:29 raise TypeError("Hook may not be instantiated directly.")30 if not is_dataclass(cls):31 raise TypeError("Subclass is not a dataclass.")32 return super().__new__(cls)33 34 def __init_subclass__(cls, **kwargs):35 # initialize .name attribute. HttpRequestHook -> http_request36 if cls.__dict__.get("name", None) is None:37 name = cls.__name__.replace("Hook", "")38 cls.name = re.sub("(?!^)([A-Z]+)", r"_\1", name).lower()39 if cls.name in all_hooks:40 other = all_hooks[cls.name]41 warnings.warn(42 f"Two conflicting event classes for {cls.name}: {cls} and {other}",43 RuntimeWarning,44 )45 if cls.name == "":46 return # don't register Hook class.47 all_hooks[cls.name] = cls48 49 # define a custom hash and __eq__ function so that events are hashable and not comparable.50 cls.__hash__ = object.__hash__ # type: ignore51 cls.__eq__ = object.__eq__ # type: ignore52 53 54all_hooks: dict[str, type[Hook]] = {}55 56 57@dataclass58class ConfigureHook(Hook):59 """60 Called when configuration changes. The updated argument is a61 set-like object containing the keys of all changed options. This62 event is called during startup with all options in the updated set.63 """64 65 updated: set[str]66 67 68@dataclass69class DoneHook(Hook):70 """71 Called when the addon shuts down, either by being removed from72 the mitmproxy instance, or when mitmproxy itself shuts down. On73 shutdown, this event is called after the event loop is74 terminated, guaranteeing that it will be the final event an addon75 sees. Note that log handlers are shut down at this point, so76 calls to log functions will produce no output.77 """78 79 80@dataclass81class RunningHook(Hook):82 """83 Called when the proxy is completely up and running. At this point,84 you can expect all addons to be loaded and all options to be set.85 """86 87 88@dataclass89class UpdateHook(Hook):90 """91 Update is called when one or more flow objects have been modified,92 usually from a different addon.93 """94 95 flows: Sequence[mitmproxy.flow.Flow]96 