33
33
from datetime import datetime
34
34
from telnetlib import Telnet
35
35
import socket
36
- import json
37
36
from typing import (
38
37
TYPE_CHECKING ,
39
38
Iterable ,
75
74
error
76
75
)
77
76
from wechaty .types import EndPoint
78
- from wechaty .utils import HookDict
77
+ from wechaty .utils import WechatySetting
79
78
80
79
from .config import config
81
80
@@ -139,15 +138,17 @@ def _list_routes_txt(app: Quart) -> List[str]:
139
138
rules = list (sorted (rules , key = lambda rule : rule .endpoint ))
140
139
141
140
headers = ("Endpoint" , "Methods" , "Websocket" , "Rule" )
142
- rule_methods = [", " .join (sorted (rule .methods )) for rule in rules if rule .methods ]
141
+ rule_methods = [", " .join (sorted (rule .methods ))
142
+ for rule in rules if rule .methods ]
143
143
144
144
widths = [
145
145
max (len (rule .endpoint ) for rule in rules ),
146
146
max (len (methods ) for methods in rule_methods ),
147
147
len ("Websocket" ),
148
148
max (len (rule .rule ) for rule in rules ),
149
149
]
150
- widths = [max (len (header ), width ) for header , width in zip (headers , widths )]
150
+ widths = [max (len (header ), width )
151
+ for header , width in zip (headers , widths )]
151
152
152
153
# pylint: disable=C0209
153
154
row = "{{0:<{0}}} | {{1:<{1}}} | {{2:<{2}}} | {{3:<{3}}}" .format (* widths )
@@ -158,7 +159,8 @@ def _list_routes_txt(app: Quart) -> List[str]:
158
159
159
160
for rule , methods in zip (rules , rule_methods ):
160
161
routes_txt .append (
161
- row .format (rule .endpoint , methods , str (rule .websocket ), rule .rule ).rstrip ()
162
+ row .format (rule .endpoint , methods , str (
163
+ rule .websocket ), rule .rule ).rstrip ()
162
164
)
163
165
return routes_txt
164
166
@@ -175,7 +177,8 @@ def _signal_handler(*_: Any) -> None: # noqa: N803
175
177
for signal_name in ["SIGINT" , "SIGTERM" , "SIGBREAK" ]:
176
178
if hasattr (signal , signal_name ):
177
179
try :
178
- loop .add_signal_handler (getattr (signal , signal_name ), _signal_handler )
180
+ loop .add_signal_handler (
181
+ getattr (signal , signal_name ), _signal_handler )
179
182
except NotImplementedError :
180
183
# Add signal handler may not be implemented on Windows
181
184
signal .signal (getattr (signal , signal_name ), _signal_handler )
@@ -397,10 +400,9 @@ def __init__(self, options: Optional[WechatyPluginOptions] = None):
397
400
self .options = options
398
401
self ._default_logger : Optional [Logger ] = None
399
402
self ._cache_dir : Optional [str ] = None
400
- self .setting_file : str = os .path .join (self .cache_dir , 'setting.json' )
401
403
402
- if not os .path .exists (self .setting_file ):
403
- self .setting = {} # type: ignore
404
+ self . setting_file : str = os .path .join (self .cache_dir , 'setting.json' )
405
+ self ._setting_wechaty_setting : WechatySetting = WechatySetting ( self . setting_file )
404
406
405
407
def metadata (self ) -> NavMetadata :
406
408
"""get the default nav metadata
@@ -417,34 +419,27 @@ def metadata(self) -> NavMetadata:
417
419
)
418
420
419
421
@property
420
- def setting (self ) -> HookDict [ str , Any ] :
422
+ def setting (self ) -> WechatySetting :
421
423
"""get the setting of a plugin"""
422
- with open (self .setting_file , 'r' , encoding = 'utf-8' ) as f :
423
- setting = json .load (f )
424
-
425
- def set_item_hooks (_ : str , __ : Any , value : dict ) -> None :
426
- """hook set_item event, and save the setting"""
427
- self ._save_setting (value )
428
-
429
- return HookDict (setting , set_item_hooks = set_item_hooks )
424
+ return self ._setting_wechaty_setting
430
425
431
- def _save_setting (self , value : dict ) -> None :
432
- """update the plugin setting"""
433
- with open (self .setting_file , 'w' , encoding = 'utf-8' ) as f :
434
- json .dump (value , f , ensure_ascii = False )
435
-
436
- @setting .setter # type: ignore
426
+ @setting .setter
437
427
def setting (self , value : dict ) -> None :
438
- """update the plugin setting"""
439
- self ._save_setting (value )
428
+ """update setting with value
429
+
430
+ Args:
431
+ value (dict): the value of setting dict
432
+ """
433
+ self ._setting_wechaty_setting .save_setting (value )
440
434
441
435
def get_ui_dir (self ) -> Optional [str ]:
442
436
"""get the ui asset dir
443
437
"""
444
438
# 1. get the customized ui dir according to the static UI_DIR attribute
445
439
if self .UI_DIR :
446
440
if os .path .exists (self .UI_DIR ):
447
- self .logger .info ("finding the UI_DIR<%s> for plugin<%s>" , self .UI_DIR , type (self ))
441
+ self .logger .info (
442
+ "finding the UI_DIR<%s> for plugin<%s>" , self .UI_DIR , type (self ))
448
443
return self .UI_DIR
449
444
450
445
# 2. get the default uidir: ui/dist
@@ -454,7 +449,8 @@ def get_ui_dir(self) -> Optional[str]:
454
449
plugin_dir = os .path .dirname (str (plugin_dir_path ))
455
450
ui_dir = os .path .join (plugin_dir , 'ui' )
456
451
if os .path .exists (ui_dir ):
457
- self .logger .info ("finding the UI_DIR<%s> for plugin<%s>" , ui_dir , type (self ))
452
+ self .logger .info (
453
+ "finding the UI_DIR<%s> for plugin<%s>" , ui_dir , type (self ))
458
454
return ui_dir
459
455
460
456
self .logger .warning (
@@ -574,7 +570,8 @@ class WechatyPluginManager: # pylint: disable=too-many-instance-attributes
574
570
def __init__ (
575
571
self , wechaty : Wechaty ,
576
572
endpoint : EndPoint ,
577
- scheduler_options : Optional [Union [AsyncIOScheduler , WechatySchedulerOptions ]] = None
573
+ scheduler_options : Optional [Union [AsyncIOScheduler ,
574
+ WechatySchedulerOptions ]] = None
578
575
):
579
576
self ._plugins : Dict [str , WechatyPlugin ] = OrderedDict ()
580
577
self ._wechaty : Wechaty = wechaty
@@ -591,9 +588,11 @@ def __init__(
591
588
scheduler = AsyncIOScheduler ()
592
589
593
590
if isinstance (scheduler_options .job_store , str ):
594
- scheduler_options .job_store = SQLAlchemyJobStore (scheduler_options .job_store )
591
+ scheduler_options .job_store = SQLAlchemyJobStore (
592
+ scheduler_options .job_store )
595
593
596
- scheduler .add_jobstore (scheduler_options .job_store , scheduler_options .job_store_alias )
594
+ scheduler .add_jobstore (
595
+ scheduler_options .job_store , scheduler_options .job_store_alias )
597
596
self .scheduler : AsyncIOScheduler = scheduler
598
597
599
598
self .static_file_cacher = StaticFileCacher ([
@@ -670,7 +669,7 @@ async def update_plugin_setting() -> Response:
670
669
return error (f'plugin<{ name } > not exist ...' )
671
670
672
671
plugin : WechatyPlugin = self ._plugins [name ]
673
- plugin .setting = data ['setting' ] # type: ignore
672
+ plugin .setting = data ['setting' ]
674
673
return success (None )
675
674
676
675
@app .route ("/js/<string:name>" , methods = ['GET' ])
@@ -842,7 +841,8 @@ async def start(self) -> None:
842
841
# re-fetch the routes info
843
842
routes_txt = _list_routes_txt (self .app )
844
843
845
- log .info ('============================starting web service========================' )
844
+ log .info (
845
+ '============================starting web service========================' )
846
846
log .info ('starting web service at endpoint: <{%s}:{%d}>' , host , port )
847
847
848
848
shutdown_trigger = await get_shutdown_trigger ()
@@ -861,7 +861,8 @@ async def start(self) -> None:
861
861
for route_txt in routes_txt :
862
862
log .info (route_txt )
863
863
864
- log .info ('============================web service has started========================' )
864
+ log .info (
865
+ '============================web service has started========================' )
865
866
866
867
# pylint: disable=too-many-locals,too-many-statements,too-many-branches
867
868
async def emit_events (self , event_name : str , * args : Any , ** kwargs : Any ) -> None :
0 commit comments