Coverage for aipyapp/plugin.py: 76%

1 from typing import Any, Callable, Dict

2 import inspect

3 from enum import Enum

4

5 from loguru import logger

6

7 from .interface import EventListener

8

9 class PluginType(Enum):

10 """插件类型"""

11 BASE = "base"

12 TASK = "task"

13 DISPLAY = "display"

14

15 class PluginError(Exception):

16 """插件异常"""

17 pass

18

19 class PluginConfigError(PluginError):

20 """插件配置异常"""

21 pass

22

23 class PluginInitError(PluginError):

24 """插件初始化异常"""

25 pass

26

27 class Plugin(EventListener):

28 """插件基类"""

29 name: str = None

30 version: str = None

31 description: str = None

32 author: str = None

33

34 def __init__(self):

35 self.logger = logger.bind(src=f"plugin.{self.name}")

36

37 @property

38 def description(self) -> str:

39 """插件描述"""

40 return self.description or self.__doc__

41

42 @property

43 def version(self) -> str:

44 """插件版本"""

45 return self.version or "1.0.0"

46

47 @property

48 def author(self) -> str:

49 """插件作者"""

50 return self.author or "Unknown"

51

52 def init(self):

53 """插件初始化逻辑

54

55 Raises:

56 PluginInitError: 插件初始化异常

57 """

58 pass

59

60 @classmethod

61 def get_type(cls) -> PluginType:

62 """Get plugin type

63

64 Returns:

65 Plugin type

66 """

67 return PluginType.BASE

68

69 def _get_methods(self, prefix: str = "fn_") -> Dict[str, Callable]:

70 """Get all functions

71

72 Returns:

73 All functions

74 """

75 return {

76 name[len(prefix):]: method

77 for name, method in inspect.getmembers(self, predicate=inspect.ismethod)

78 if name.startswith(prefix) and len(name) > len(prefix)

79 }

80

81 def get_handlers(self) -> Dict[str, Callable]:

82 """Get all handlers

83

84 Returns:

85 All handlers

86 """

87 return self._get_methods(prefix='on_')

88

89 class TaskPlugin(Plugin):

90 """任务插件"""

91 def __init__(self, config: Dict[str, Any] = None):

92 super().__init__()

93 self.config = config or {}

94

95 @classmethod

96 def get_type(cls) -> PluginType:

97 """Get plugin type

98

99 Returns:

100 Plugin type

101 """

102 return PluginType.TASK

103

104 def get_functions(self) -> Dict[str, Callable]:

105 """Get all functions

106

107 Returns:

108 All functions

109 """

110 return self._get_methods(prefix='fn_')

111