Просмотр исходного кода

feat(notify): Interface implemented but not yet connected to the system

runhey 3 лет назад
Родитель
Сommit
984ea8e12c

+ 6 - 0
module/config/config.py

@@ -7,6 +7,7 @@ import operator
 import threading
 
 from datetime import datetime
+from cached_property import cached_property
 
 from module.base.filter import Filter
 from module.config.config_updater import ConfigUpdater
@@ -17,6 +18,7 @@ from module.config.config_model import ConfigModel
 from module.config.config_state import ConfigState
 from module.config.scheduler import TaskScheduler
 from module.config.utils import *
+from module.notify.notify import Notifier
 
 from module.exception import RequestHumanTakeover, ScriptError
 from module.logger import logger
@@ -313,6 +315,10 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         scheduler.next_run = next_run
         self.save()
 
+    @cached_property
+    def notifier(self):
+        return Notifier(self.model.script.error.notify_config)
+
 if __name__ == '__main__':
     config = Config(config_name='oas1')
     config.update_scheduler()

+ 12 - 1
module/gui/context/utils.py

@@ -22,7 +22,18 @@ class Utils(QObject):
         """
         return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
-
+    @Slot(str, str, str, result="QString")
+    def test_notify(self, _config: str, title: str, content: str) -> bool:
+        from module.notify.notify import Notifier
+        try:
+            notifier = Notifier(_config)
+            if notifier.push(title=title, content=content):
+                return "true"
+            else:
+                return "false"
+        except Exception as e:
+            logger.exception(e)
+            return "false"
 
 
 

+ 1 - 0
module/gui/qml.qrc

@@ -33,5 +33,6 @@
         <file>qml/Component/RuleFile.qml</file>
         <file>qml/Content/ListRule.qml</file>
         <file>qml/Component/RuleFile2.qml</file>
+        <file>qml/Content/NotifyTest.qml</file>
     </qresource>
 </RCC>

+ 81 - 0
module/gui/qml/Content/NotifyTest.qml

@@ -0,0 +1,81 @@
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Layouts
+import FluentUI
+
+
+FluScrollablePage{
+    leftPadding:10
+    rightPadding:10
+    bottomPadding:20
+    spacing: 6
+
+    FluText{
+        text: '消息推送测试'
+        font: FluTextStyle.Title
+    }
+    FluArea{
+        Layout.fillWidth: true
+        height: 500
+        paddings: 10
+
+        ColumnLayout{
+            id: yyyyy
+            spacing: 10
+            anchors{
+                top: parent.top
+                left: parent.left
+            }
+            width: parent.width
+            property int conentWith: 300
+            FluText{
+                text: '推送配置'
+                font: FluTextStyle.BodyStrong
+            }
+            FluMultilineTextBox{
+                id: notifyConfig
+                implicitWidth: yyyyy.conentWith
+                placeholderText: 'Please input your notify config'
+                text: 'provider: null'
+
+            }
+            FluText{
+                text: '请翻阅文档[消息推送]进行填写上方的参数设置。 \n请填写下方的Title和Conent后点击发送消息测试 \n注意这并不会在当前界面有任何反馈'
+            }
+            FluText{
+                text: '主题'
+                font: FluTextStyle.BodyStrong
+            }
+            FluTextBox{
+                id: notifyTitle
+                implicitWidth: yyyyy.conentWith
+                placeholderText: 'Title'
+                text: 'TEST TITLE'
+            }
+            FluText{
+                text: '内容'
+                font: FluTextStyle.BodyStrong
+            }
+            FluMultilineTextBox{
+                id: notifyConent
+                implicitWidth: yyyyy.conentWith
+                placeholderText: 'Conent'
+                text: 'TEST conent'
+            }
+            FluFilledButton{
+                id: testSend
+                implicitWidth: yyyyy.conentWith
+                text: '测试发送'
+                onClicked: {
+                    const result = utils.test_notify(notifyConfig.text, notifyTitle.text, notifyConent.text)
+                    console.debug(result)
+                    if(result === "true"){
+                        showSuccess('Successful')
+                    }else{
+                        showError('Failure')
+                    }
+                }
+            }
+        }
+    }
+}

+ 15 - 8
module/gui/qml/Page/O_Home.qml

@@ -12,20 +12,27 @@ SplitPanel{
     property string configName: ""
 
     onTitleChanged: {
-        if(title === qsTr("Home")){
-            var comp = Qt.createComponent("../../qml/Page/Home.qml")
-            if (comp.status === Component.Ready) {
-                setLoader(comp)
-            }
-        }else if(title === qsTr("Update")){
-            var updater = Qt.createComponent("../../qml/Page/Update.qml")
+        if(title === "Home"){
+//            const comp = Qt.createComponent("../../qml/Page/Home.qml")
+//            if (comp.status === Component.Ready) {
+//                setLoader(comp)
+
+//            }
+            showDefalut()
+        }else if(title === "Update"){
+            const updater = Qt.createComponent("../../qml/Page/Update.qml")
             if (updater.status === Component.Ready) {
                 setLoader(updater)
             }
+        }else if(title === "NotifyTest"){
+            const notify_test = Qt.createComponent("../../qml/Content/NotifyTest.qml")
+            if (notify_test.status === Component.Ready) {
+                setLoader(notify_test)
+            }
         }
     }
     Component.onCompleted:{
-        var data = { "Home":[], 'Update': []}
+        var data = { "Home":[], 'Update': [], 'NotifyTest':[]}
         create(data)
 
         var comp = Qt.createComponent("../../qml/Page/Home.qml")

+ 69 - 52
module/notify/notify.py

@@ -11,69 +11,86 @@ from onepush.providers.custom import Custom
 from requests import Response
 
 from module.logger import logger
-
 onepush.core.log = logger
 
 
-def handle_notify(_config: str, **kwargs) -> bool:
-    try:
-        config = {}
-        for item in yaml.safe_load_all(_config):
-            config.update(item)
-    except Exception:
-        logger.error("Fail to load onepush config, skip sending")
-        return False
-    try:
-        provider_name: str = config.pop("provider", None)
-        if provider_name is None:
-            logger.info("No provider specified, skip sending")
-            return False
-        notifier: Provider = get_notifier(provider_name)
-        required: list[str] = notifier.params["required"]
-        config.update(kwargs)
+class Notifier:
+    def __init__(self, _config: str) -> None:
+        try:
+            config = {}
+            for item in yaml.safe_load_all(_config):
+                config.update(item)
+        except Exception:
+            logger.error("Fail to load onepush config, skip sending")
+            return
+        self.config = config
+        try:
+            # 获取provider
+            self.provider_name: str = self.config.pop("provider", None)
+            if self.provider_name is None:
+                logger.info("No provider specified, skip sending")
+                return
+            # 获取notifier
+            self.notifier: Provider = get_notifier(self.provider_name)
+            # 获取notifier的必填参数
+            self.required: list[str] = self.notifier.params["required"]
+        except OnePushException:
+            logger.exception("Init notifier failed")
+            return
+        except Exception as e:
+            logger.exception(e)
+            return
 
+    def push(self, **kwargs) -> bool:
+        # 更新配置
+        self.config.update(kwargs)
         # pre check
-        for key in required:
-            if key not in config:
+        for key in self.required:
+            if key not in self.config:
                 logger.warning(
-                    f"Notifier {notifier.name} require param '{key}' but not provided"
+                    f"Notifier {self.notifier.name} require param '{key}' but not provided"
                 )
 
-        if isinstance(notifier, Custom):
-            if "method" not in config or config["method"] == "post":
-                config["datatype"] = "json"
-            if not ("data" in config or isinstance(config["data"], dict)):
-                config["data"] = {}
+        if isinstance(self.notifier, Custom):
+            if "method" not in self.config or self.config["method"] == "post":
+                self.config["datatype"] = "json"
+            if not ("data" in self.config or isinstance(self.config["data"], dict)):
+                self.config["data"] = {}
             if "title" in kwargs:
-                config["data"]["title"] = kwargs["title"]
+                self.config["data"]["title"] = kwargs["title"]
             if "content" in kwargs:
-                config["data"]["content"] = kwargs["content"]
+                self.config["data"]["content"] = kwargs["content"]
 
-        if provider_name.lower() == "gocqhttp":
-            access_token = config.get("access_token")
+        if self.provider_name.lower() == "gocqhttp":
+            access_token = self.config.get("access_token")
             if access_token:
-                config["token"] = access_token
+                self.config["token"] = access_token
+
+
+        try:
+            resp = self.notifier.notify(**self.config)
+            if isinstance(resp, Response):
+                if resp.status_code != 200:
+                    logger.warning("Push notify failed!")
+                    logger.warning(f"HTTP Code:{resp.status_code}")
+                    return False
+                else:
+                    if self.provider_name.lower() == "gocqhttp":
+                        return_data: dict = resp.json()
+                        if return_data["status"] == "failed":
+                            logger.warning("Push notify failed!")
+                            logger.warning(
+                                f"Return message:{return_data['wording']}")
+                            return False
+        except OnePushException:
+            logger.exception("Push notify failed")
+            return False
+        except Exception as e:
+            logger.exception(e)
+            return False
+
+        logger.info("Push notify success")
+        return True
+
 
-        resp = notifier.notify(**config)
-        if isinstance(resp, Response):
-            if resp.status_code != 200:
-                logger.warning("Push notify failed!")
-                logger.warning(f"HTTP Code:{resp.status_code}")
-                return False
-            else:
-                if provider_name.lower() == "gocqhttp":
-                    return_data: dict = resp.json()
-                    if return_data["status"] == "failed":
-                        logger.warning("Push notify failed!")
-                        logger.warning(
-                            f"Return message:{return_data['wording']}")
-                        return False
-    except OnePushException:
-        logger.exception("Push notify failed")
-        return False
-    except Exception as e:
-        logger.exception(e)
-        return False
 
-    logger.info("Push notify success")
-    return True

+ 0 - 2
script.py

@@ -69,8 +69,6 @@ class Script:
             logger.exception(e)
             exit(1)
 
-
-
     @cached_property
     def checker(self):
         """