This repository has been archived by the owner on Dec 19, 2024. It is now read-only.
forked from GraiaProject/Avilla
-
Notifications
You must be signed in to change notification settings - Fork 1
/
application.py
293 lines (241 loc) · 11.2 KB
/
application.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from __future__ import annotations
import asyncio
import signal
from typing import TYPE_CHECKING, Any, Callable, Iterable, TypeVar, overload
from creart import it
from graia.amnesia.builtins.memcache import MemcacheService
from graia.broadcast import Broadcast
from launart import Launart
from launart.service import Service
from loguru import logger
from avilla.core._runtime import get_current_avilla
from avilla.core.account import AccountInfo, BaseAccount
from avilla.core.dispatchers import AvillaBuiltinDispatcher
from avilla.core.event import MetadataModified
from avilla.core.protocol import BaseProtocol
from avilla.core.ryanvk.staff import Staff
from avilla.core.selector import Selector
from avilla.core.service import AvillaService
from avilla.core.utilles import identity
from avilla.standard.core.activity import ActivityEvent
from avilla.standard.core.request import RequestEvent
if TYPE_CHECKING:
from graia.broadcast import Decorator, Dispatchable, Namespace, T_Dispatcher
from avilla.core.event import AvillaEvent
from avilla.standard.core.application import AvillaLifecycleEvent
from .resource import Resource
T = TypeVar("T")
TE = TypeVar("TE", bound="AvillaEvent")
TP = TypeVar("TP", bound=BaseProtocol)
class Avilla:
broadcast: Broadcast
launch_manager: Launart
protocols: list[BaseProtocol]
accounts: dict[Selector, AccountInfo]
service: AvillaService
global_artifacts: dict[Any, Any]
def __init__(
self,
*,
broadcast: Broadcast | None = None,
launch_manager: Launart | None = None,
message_cache_size: int = 300,
record_send: bool = True,
):
self.broadcast = broadcast or it(Broadcast)
self.launch_manager = launch_manager or it(Launart)
self.protocols = []
self._protocol_map = {}
self.accounts = {}
self.service = AvillaService(self, message_cache_size)
self.global_artifacts = {}
self.launch_manager.add_component(MemcacheService())
self.launch_manager.add_component(self.service)
self.broadcast.finale_dispatchers.append(AvillaBuiltinDispatcher(self))
self.__init_isolate__()
if message_cache_size > 0:
from avilla.core.context import Context
from avilla.core.message import Message
from avilla.standard.core.account import AccountUnregistered
from avilla.standard.core.message import MessageReceived
@self.broadcast.receiver(MessageReceived)
async def message_cacher(context: Context, message: Message):
if context.account.info.enabled_message_cache:
self.service.message_cache[context.account.route].push(message)
@self.broadcast.receiver(AccountUnregistered)
async def clear_cache(event: AccountUnregistered):
if event.account.route in self.service.message_cache:
del self.service.message_cache[event.account.route]
message_cacher.__annotations__ = {"context": Context, "message": Message}
clear_cache.__annotations__ = {"event": AccountUnregistered}
if record_send:
from avilla.core.context import Context
from avilla.core.message import Message
from avilla.standard.core.message import MessageSent
@self.broadcast.receiver(MessageSent)
async def message_sender(context: Context, message: Message):
scene = f"{'.'.join(f'{k}({v})' for k, v in context.scene.items())}"
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"{scene} <- {str(message.content)!r}"
)
message_sender.__annotations__ = {"context": Context, "message": Message}
self.custom_event_recorder: dict[type[AvillaEvent], Callable[[AvillaEvent], None]] = {}
def event_record(self, event: AvillaEvent | AvillaLifecycleEvent):
from avilla.standard.core.account.event import AccountStatusChanged
from avilla.standard.core.application import AvillaLifecycleEvent
from avilla.standard.core.message import (
MessageEdited,
MessageReceived,
MessageSent,
)
if isinstance(event, AccountStatusChanged):
logger.debug(
f"[{event.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{event.account.route['account']}]: "
f"{event.__class__.__name__}"
)
return
if isinstance(event, AvillaLifecycleEvent):
logger.debug(event.__class__.__name__)
return
context = event.context
client = context.client.display
scene = context.scene.display
endpoint = context.endpoint.display
if isinstance(event, MessageSent):
return
if type(event) in self.custom_event_recorder:
self.custom_event_recorder[type(event)](event)
elif isinstance(event, RequestEvent):
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"Request {event.request.request_type or event.request.id}"
f"{f' with {event.request.message}' if event.request.message else ''} "
f"from {client} in {scene}"
)
elif isinstance(event, ActivityEvent):
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"Activity {event.id}: {event.activity}"
f"from {client} in {scene}"
)
elif isinstance(event, MetadataModified):
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"Metadata {event.route} Modified: {event.details}"
f"from {client} in {scene}"
)
elif isinstance(event, MessageReceived):
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"{scene} -> {str(event.message.content)!r}"
)
elif isinstance(event, MessageEdited):
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"{scene} => {str(event.past)!r} -> {str(event.current)!r}"
)
else:
logger.info(
f"[{context.account.info.protocol.__class__.__name__.replace('Protocol', '')} "
f"{context.account.route['account']}]: "
f"{event.__class__.__name__} from {client} to {endpoint} in {scene}"
)
@overload
def add_event_recorder(self, event_type: type[TE]) -> Callable[[Callable[[TE], None]], Callable[[TE], None]]:
...
@overload
def add_event_recorder(self, event_type: type[TE], recorder: Callable[[TE], None]) -> Callable[[TE], None]:
...
def add_event_recorder(
self, event_type: type[TE], recorder: Callable[[TE], None] | None = None
) -> Callable[..., Callable[[TE], None]] | Callable[[TE], None]:
if recorder is None:
def wrapper(func: Callable[[TE], None]):
self.custom_event_recorder[event_type] = func # type: ignore
return func
return wrapper
self.custom_event_recorder[event_type] = recorder # type: ignore
return recorder
def __init_isolate__(self):
from avilla.core.builtins.resource_fetch import CoreResourceFetchPerform
CoreResourceFetchPerform.apply_to(self.global_artifacts)
def get_staff_components(self):
return {"avilla": self}
def get_staff_artifacts(self):
return [self.global_artifacts]
def __staff_generic__(self, element_type: dict, event_type: dict):
...
@classmethod
def current(cls):
return get_current_avilla()
async def fetch_resource(self, resource: Resource[T]) -> T:
return await Staff(self.get_staff_artifacts(), self.get_staff_components()).fetch_resource(resource)
def get_account(self, target: Selector) -> AccountInfo:
return self.accounts[target]
@overload
def get_accounts(self, *, land: str) -> list[AccountInfo]:
...
@overload
def get_accounts(self, *, pattern: str) -> list[AccountInfo]:
...
@overload
def get_accounts(self, *, protocol_type: type[BaseProtocol] | tuple[type[BaseProtocol], ...]) -> list[AccountInfo]:
...
@overload
def get_accounts(self, *, account_type: type[BaseAccount] | tuple[type[BaseAccount], ...]) -> list[AccountInfo]:
...
def get_accounts(
self,
*,
land: str | None = None,
pattern: str | None = None,
protocol_type: type[BaseProtocol] | tuple[type[BaseProtocol], ...] | None = None,
account_type: type[BaseAccount] | tuple[type[BaseAccount], ...] | None = None,
) -> list[AccountInfo]:
if land:
return [account for account in self.accounts.values() if account.platform.land.name == land]
if pattern:
return [account for selector, account in self.accounts.items() if selector.follows(pattern)]
if protocol_type:
return [account for account in self.accounts.values() if isinstance(account.protocol, protocol_type)]
if account_type:
return [account for account in self.accounts.values() if isinstance(account.account, account_type)]
raise ValueError("No filter is specified")
def _update_protocol_map(self):
self._protocol_map = {type(i): i for i in self.protocols}
def apply_protocols(self, *protocols: BaseProtocol) -> None:
self.protocols.extend(protocols)
self._update_protocol_map()
for protocol in protocols:
protocol.ensure(self)
def get_protocol(self, protocol_type: type[TP]) -> TP:
if protocol_type not in self._protocol_map:
raise ValueError(f"{identity(protocol_type)} is unregistered on this Avilla instance")
return self._protocol_map[protocol_type] # type: ignore
def apply_services(self, *services: Service):
for i in services:
self.launch_manager.add_component(i)
def listen(
self,
event: type[Dispatchable],
priority: int = 16,
dispatchers: list[T_Dispatcher] | None = None,
namespace: Namespace | None = None,
decorators: list[Decorator] | None = None,
):
return self.broadcast.receiver(event, priority, dispatchers, namespace, decorators)
def launch(
self,
*,
loop: asyncio.AbstractEventLoop | None = None,
stop_signal: Iterable[signal.Signals] = (signal.SIGINT,),
):
self.launch_manager.launch_blocking(loop=loop, stop_signal=stop_signal)