summaryrefslogtreecommitdiff
path: root/ATRI/service.py
blob: ab870fd085273f62230e25bbf992c871d98f9378 (plain)
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import os
import json
from pathlib import Path
from datetime import datetime
from typing import (
    Dict,
    Any,
    List,
    Set,
    Tuple,
    Type,
    Union,
    Optional,
    TYPE_CHECKING
)
from nonebot.matcher import Matcher
from nonebot.permission import Permission
from nonebot.typing import T_State, T_Handler, T_RuleChecker
from nonebot.rule import Rule, command, keyword

from .log import logger as log
from .config import config
from .utils.request import post_bytes

if TYPE_CHECKING:
    from nonebot.adapters import Bot, Event


SERVICE_DIR = Path('.') / 'ATRI' / 'data' / 'service'
SERVICES_DIR = SERVICE_DIR / 'services'
os.makedirs(SERVICE_DIR, exist_ok=True)
os.makedirs(SERVICES_DIR, exist_ok=True)


matcher_list: list = []
is_sleep: bool = False


def _load_block_list() -> dict:
    file_name = "ban.json"
    file = SERVICE_DIR / file_name
    try:
        data = json.loads(file.read_bytes())
    except:
        data = {
            "user": [],
            "group": []
        }
        with open(file, "w") as r:
            r.write(json.dumps(data, indent=4))
    return data


def _save_block_list(data: dict) -> None:
    file_name = "ban.json"
    file = SERVICE_DIR / file_name
    with open(file, "w") as r:
        r.write(json.dumps(data, indent=4))


def _load_service_config(service: str, docs: str = None) -> dict:
    file_name = service + ".json"
    file = SERVICES_DIR / file_name
    try:
        data = json.loads(file.read_bytes())
    except:
        service_info = {
            "name": service,
            "docs": docs,
            "disable_user": _load_block_list()['user'],
            "disable_group": _load_block_list()['group']
        }
        with open(file, "w") as r:
            r.write(json.dumps(service_info, indent=4))
        data = service_info
    return data


def _save_service_config(service: str, data: dict) -> None:
    file_name = service + ".json"
    file = SERVICES_DIR / file_name
    with open(file, "w") as r:
        r.write(json.dumps(data, indent=4))


class Service:
    """
    集成一套服务管理,block准确至个人
    计划搭配前端使用
    """
    @staticmethod
    def manual_reg_service(service: str):
        file_name = service + ".json"
        file = SERVICES_DIR / file_name
        service_info = {
            "name": service,
            "docs": None,
            "disable_user": _load_block_list()['user'],
            "disable_group": _load_block_list()['group']
        }
        with open(file, "w") as r:
            r.write(json.dumps(service_info, indent=4))
    
    @staticmethod
    def auth_service(service: str, group: Optional[int] = None) -> bool:
        data = _load_service_config(service)
        return False if group in data["disable_group"] else True
    
    @staticmethod
    def control_service(service: str, group: int, is_enable: bool) -> None:
        data = _load_service_config(service)
        sv_group = data.get('disable_group', [])
        if is_enable:
            sv_group.remove(group)
            log.info(f"Service {service} has been enabled.")
        else:
            sv_group.append(group)
            log.info(f"Service {service} has been disabled.")
        data["disable_group"] = sv_group
        _save_service_config(service, data)
    
    @staticmethod
    def on_message(rule: Optional[Union[Rule, T_RuleChecker]] = None,
                   permission: Optional[Permission] = None,
                   *,
                   handlers: Optional[List[T_Handler]] = None,
                   temp: bool = False,
                   priority: int = 1,
                   block: bool = True,
                   state: Optional[T_State] = None) -> Type[Matcher]:
        matcher = Matcher.new("message",
                              Rule() & rule,
                              permission or Permission(),
                              temp=temp,
                              priority=priority,
                              block=block,
                              handlers=handlers,
                              default_state=state)
        return matcher

    @staticmethod
    def on_notice(name: str,
                  docs: Optional[str] = None,
                  rule: Optional[Union[Rule, T_RuleChecker]] = None,
                  *,
                  handlers: Optional[List[T_Handler]] = None,
                  temp: bool = False,
                  priority: int = 1,
                  block: bool = False,
                  state: Optional[T_State] = None) -> Type[Matcher]:
        matcher = Matcher.new("notice",
                              Rule() & rule,
                              Permission(),
                              temp=temp,
                              priority=priority,
                              block=block,
                              handlers=handlers,
                              default_state=state)
        _load_service_config(name, docs)
        matcher_list.append(name)
        return matcher

    @staticmethod
    def on_request(name: str,
                   docs: Optional[str] = None,
                   rule: Optional[Union[Rule, T_RuleChecker]] = None,
                   *,
                   handlers: Optional[List[T_Handler]] = None,
                   temp: bool = False,
                   priority: int = 1,
                   block: bool = False,
                   state: Optional[T_State] = None) -> Type[Matcher]:
        matcher = Matcher.new("request",
                              Rule() & rule,
                              Permission(),
                              temp=temp,
                              priority=priority,
                              block=block,
                              handlers=handlers,
                              default_state=state)
        _load_service_config(name, docs)
        matcher_list.append(name)
        return matcher

    @classmethod
    def on_command(cls,
                   name: str,
                   cmd: Union[str, Tuple[str, ...]],
                   docs: Optional[str] = None,
                   rule: Optional[Union[Rule, T_RuleChecker]] = None,
                   aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None,
                   **kwargs) -> Type[Matcher]:
        async def _strip_cmd(bot: "Bot", event: "Event", state: T_State):
            message = event.get_message()
            segment = message.pop(0)
            new_message = message.__class__(
                str(segment).lstrip()
                [len(state["_prefix"]["raw_command"]):].lstrip())  # type: ignore
            for new_segment in reversed(new_message):
                message.insert(0, new_segment)
        
        handlers = kwargs.pop("handlers", [])
        handlers.insert(0, _strip_cmd)
        
        commands = set([cmd]) | (aliases or set())
        _load_service_config(name, docs)
        matcher_list.append(name)
        return cls.on_message(command(*commands) & rule,
                              handlers=handlers, **kwargs)

    @classmethod
    def on_keyword(cls,
                   name: str,
                   keywords: Set[str],
                   docs: Optional[str] = None,
                   rule: Optional[Union[Rule, T_RuleChecker]] = None,
                   **kwargs) -> Type[Matcher]:
        _load_service_config(name, docs)
        matcher_list.append(name)
        return cls.on_message(keyword(*keywords) & rule, **kwargs)
    
    
    class NetworkPost:
        URL = (
            f"http://{config['NetworkPost']['host']}:"
            f"{config['NetworkPost']['port']}/"
        )
        
        @classmethod
        async def send_private_msg(cls,
                                user_id: int,
                                message: str,
                                auto_escape: bool = False): # -> Dict[str, Any]
            url = cls.URL + "send_private_msg?"
            params = {
                "user_id": user_id,
                "message": message,
                "auto_escape": f"{auto_escape}"
            }
            result = json.loads(await post_bytes(url, params))
            log.debug(result)
            return result

        @classmethod
        def send_group_msg(cls,
                        group_id: int,
                        message: Union[str],
                        auto_escape: Optional[bool] = ...) -> Dict[str, Any]:
            ...

        @classmethod
        def send_msg(cls,
                    message_type: Optional[str] = ...,
                    user_id: Optional[int] = ...,
                    group_id: Optional[int] = ...,
                    message = Union[str],
                    auto_escape: bool = ...) -> Dict[str, Any]:
            ...

        @classmethod
        def delete_msg(cls,
                    message_id: int):
            ...

        @classmethod
        def get_msg(cls,
                    message_id: int) -> Dict[str, Any]:
            ...

        @classmethod
        def get_forward_msg(cls,
                            id: int):
            ...

        @classmethod
        def send_like(cls,
                    user_id: int,
                    times: int = ...):
            ...

        @classmethod
        def set_group_kick(cls,
                        group_id: int,
                        user_id: int,
                        reject_add_request: bool = ...):
            ...

        @classmethod
        def set_group_ban(cls,
                        group_id: int,
                        user_id: int,
                        duration: int = ...):
            ...

        @classmethod
        def set_group_anonymous_ban(cls,
                                    group_id: int,
                                    anonymous: Optional[Dict[str, Any]] = ...,
                                    flag: Optional[str] = ...,
                                    duration: int = ...):
            ...

        @classmethod
        def set_group_whole_ban(cls,
                                group_id: int,
                                enable: bool = ...):
            ...

        @classmethod
        def set_group_admin(cls,
                            group_id: int,
                            user_id: int,
                            enable: bool = ...):
            ...

        @classmethod
        def set_group_anonymous(cls,
                                group_id: int,
                                enable: bool = ...):
            ...
        
        @classmethod
        def set_group_card(cls):
            ...

        @classmethod
        def set_group_name(cls):
            ...
        
        @classmethod
        def set_group_leave(cls):
            ...
        
        @classmethod
        def set_group_special_title(cls):
            ...
        
        @classmethod
        def set_friend_add_request(cls):
            ...
        
        @classmethod
        def set_group_add_request(cls):
            ...

        @classmethod
        def get_login_info(cls):
            ...
        
        @classmethod
        def get_stranger_info(cls):
            ...
        
        @classmethod
        def get_friend_list(cls):
            ...
        
        @classmethod
        def get_group_info(cls):
            ...
        
        @classmethod
        def get_group_list(cls):
            ...
        
        @classmethod
        def get_group_member_info(cls):
            ...
        
        @classmethod
        def get_group_member_list(cls):
            ...

        @classmethod
        def get_group_honor_info(cls):
            ...
        
        @classmethod
        def get_cookies(cls):
            ...
        
        @classmethod
        def get_csrf_token(cls):
            ...
        
        @classmethod
        def get_credentials(cls):
            ...
        
        @classmethod
        def get_record(cls):
            ...
        
        @classmethod
        def get_image(cls):
            ...
        
        @classmethod
        def can_send_image(cls):
            ...
        
        @classmethod
        def can_send_record(cls):
            ...
        
        @classmethod
        def get_status(cls):
            ...
        
        @classmethod
        def get_version_info(cls):
            ...
        
        @classmethod
        def set_restart(cls):
            ...
        
        @classmethod
        def clean_cache(cls):
            ...
    
    
    class Dormant:
        @staticmethod
        def is_dormant() -> bool:
            return False if is_sleep else True
        
        @staticmethod
        def control_dormant(is_enable: bool) -> None:
            global is_sleep
            if is_enable:
                is_sleep = True
            else:
                is_sleep = False
    
    
    class BlockSystem:
        file_name = "ban.json"
        path = SERVICE_DIR / file_name
        
        @classmethod
        def auth_user(cls, user: int) -> bool:
            return False if user in _load_block_list()['user'] else True
        
        @staticmethod
        def auth_group(group: int) -> bool:
            return False if group in _load_block_list()['group'] else True
        
        @classmethod
        def control_list(cls,
                         is_enable: bool,
                         user: Optional[int] = None,
                         group: Optional[int] = None) -> None:
            data = _load_block_list()
            if user:
                if is_enable:
                    data['user'][user] = datetime.now().__str__
                    log.info(f"New blocked user: {user} | Time: {datetime.now()}")
                else:
                    del data[user]
                    log.info(f"User {user} has been unblock.")
            elif group:
                if is_enable:
                    data['group'][group] = datetime.now().__str__
                    log.info(f"New blocked group: {group} | Time: {datetime.now()}")
                else:
                    del data[user]
                    log.info(f"Group {group} has been unblock.")
            
            with open(cls.path, "w") as r:
                json.dump(data, r)