|
| 1 | +import asyncio |
| 2 | +import threading |
| 3 | +from typing import Optional |
| 4 | +from loguru import logger |
| 5 | + |
| 6 | +from app.tools.path_utils import get_data_path |
| 7 | + |
| 8 | +CSHARP_AVAILABLE = False |
| 9 | + |
| 10 | +try: |
| 11 | + # 导入 Python.NET |
| 12 | + from pythonnet import load |
| 13 | + load("coreclr", runtime_config=get_data_path("dlls", "dotnet.runtimeconfig.json")) |
| 14 | + |
| 15 | + # 加载 .NET CoreCLR 程序集 |
| 16 | + import clr |
| 17 | + clr.AddReference("ClassIsland.Shared.IPC") |
| 18 | + clr.AddReference("SecRandom4Ci.Interface") |
| 19 | + |
| 20 | + # 导入程序集 |
| 21 | + from System import Action |
| 22 | + from ClassIsland.Shared.Enums import TimeState |
| 23 | + from ClassIsland.Shared.IPC import IpcClient, IpcRoutedNotifyIds |
| 24 | + from ClassIsland.Shared.IPC.Abstractions.Services import IPublicLessonsService |
| 25 | + from dotnetCampus.Ipc.CompilerServices.GeneratedProxies import GeneratedIpcFactory |
| 26 | + from SecRandom4Ci.Interface.Services import ISecRandomService |
| 27 | + from SecRandom4Ci.Interface.Models import CallResult, Student |
| 28 | + |
| 29 | + CSHARP_AVAILABLE = True |
| 30 | +except: |
| 31 | + logger.warning("无法加载 Python.NET,将会回滚!") |
| 32 | + |
| 33 | + |
| 34 | +if CSHARP_AVAILABLE: |
| 35 | + class CSharpIPCHandler: |
| 36 | + """C# dotnetCampus.Ipc 处理器,用于连接 ClassIsland 实例""" |
| 37 | + _instance: Optional["CSharpIPCHandler"] = None |
| 38 | + |
| 39 | + def __new__(cls): |
| 40 | + if cls._instance is None: |
| 41 | + cls._instance = super().__new__(cls) |
| 42 | + cls._instance._initialized = False |
| 43 | + return cls._instance |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def instance(cls): |
| 47 | + """获取单例实例""" |
| 48 | + if cls._instance is None: |
| 49 | + cls._instance = cls() |
| 50 | + return cls._instance |
| 51 | + |
| 52 | + def __init__(self): |
| 53 | + """ |
| 54 | + 初始化 C# IPC 处理器 |
| 55 | + """ |
| 56 | + self.ipc_client: Optional[IpcClient] = None |
| 57 | + self.client_thread: Optional[threading.Thread] = None |
| 58 | + self.is_running = False |
| 59 | + |
| 60 | + def start_ipc_client(self) -> bool: |
| 61 | + """ |
| 62 | + 启动 C# IPC 客户端 |
| 63 | +
|
| 64 | + Returns: |
| 65 | + 启动成功返回True,失败返回False |
| 66 | + """ |
| 67 | + if self.is_running: |
| 68 | + return True |
| 69 | + |
| 70 | + try: |
| 71 | + self.client_thread = threading.Thread(target=self._run_client, daemon=False) |
| 72 | + self.client_thread.start() |
| 73 | + self.is_running = True |
| 74 | + return True |
| 75 | + except Exception as e: |
| 76 | + logger.error(f"启动 C# IPC 客户端失败: {e}") |
| 77 | + return False |
| 78 | + |
| 79 | + def stop_ipc_client(self): |
| 80 | + """停止 C# IPC 客户端""" |
| 81 | + self.is_running = False |
| 82 | + if self.client_thread and self.client_thread.is_alive(): |
| 83 | + self.client_thread.join(timeout=1) |
| 84 | + |
| 85 | + def send_notification( |
| 86 | + self, |
| 87 | + class_name, |
| 88 | + selected_students, |
| 89 | + draw_count=1, |
| 90 | + settings=None, |
| 91 | + settings_group=None |
| 92 | + ) -> bool: |
| 93 | + """发送提醒""" |
| 94 | + |
| 95 | + if settings: |
| 96 | + display_duration = settings.get("notification_display_duration", 5) |
| 97 | + else: |
| 98 | + display_duration = 5 |
| 99 | + |
| 100 | + randomService = GeneratedIpcFactory.CreateIpcProxy[ISecRandomService]( |
| 101 | + self.ipc_client.Provider, self.ipc_client.PeerProxy) |
| 102 | + result = self.convert_to_call_result(class_name, selected_students, draw_count, display_duration) |
| 103 | + randomService.NotifyResult(result) |
| 104 | + |
| 105 | + return True |
| 106 | + |
| 107 | + def is_breaking(self) -> bool: |
| 108 | + """是否处于下课时间""" |
| 109 | + lessonSc = GeneratedIpcFactory.CreateIpcProxy[IPublicLessonsService]( |
| 110 | + self.ipc_client.Provider, self.ipc_client.PeerProxy) |
| 111 | + state = lessonSc.CurrentState in [getattr(TimeState, "None"), TimeState.PrepareOnClass, TimeState.Breaking, TimeState.AfterSchool] |
| 112 | + logger.debug(f"获取到的 ClassIsland 时间状态: {lessonSc.CurrentState} 是否下课: {state}") |
| 113 | + return state |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def convert_to_call_result(class_name: str, selected_students, draw_count: int, display_duration=5.0) -> CallResult: |
| 117 | + result = CallResult() |
| 118 | + result.ClassName = class_name |
| 119 | + result.DrawCount = draw_count |
| 120 | + result.DisplayDuration = display_duration |
| 121 | + for student in selected_students: |
| 122 | + cs_student = Student() |
| 123 | + cs_student.StudentId = student[0] |
| 124 | + cs_student.StudentName = student[1] |
| 125 | + cs_student.Exists = student[2] |
| 126 | + result.SelectedStudents.Add(cs_student) |
| 127 | + return result |
| 128 | + |
| 129 | + def _on_class_test(self): |
| 130 | + lessonSc = GeneratedIpcFactory.CreateIpcProxy[IPublicLessonsService]( |
| 131 | + self.ipc_client.Provider, self.ipc_client.PeerProxy) |
| 132 | + logger.debug(f"上课 {lessonSc.CurrentSubject.Name} 时间: {lessonSc.CurrentTimeLayoutItem}") |
| 133 | + |
| 134 | + def _run_client(self): |
| 135 | + """运行 C# IPC 客户端""" |
| 136 | + |
| 137 | + async def client(): |
| 138 | + """异步客户端""" |
| 139 | + |
| 140 | + self.ipc_client = IpcClient() |
| 141 | + self.ipc_client.JsonIpcProvider.AddNotifyHandler(IpcRoutedNotifyIds.OnClassNotifyId, Action(lambda: self._on_class_test())) |
| 142 | + |
| 143 | + task = self.ipc_client.Connect() |
| 144 | + await loop.run_in_executor(None, lambda: task.Wait()) |
| 145 | + |
| 146 | + while self.is_running: |
| 147 | + await asyncio.sleep(1) |
| 148 | + |
| 149 | + self.ipc_client = None |
| 150 | + |
| 151 | + # 启动新的 asyncio 事件循环 |
| 152 | + loop = asyncio.new_event_loop() |
| 153 | + asyncio.set_event_loop(loop) |
| 154 | + loop.run_until_complete(client()) |
| 155 | + loop.close() |
| 156 | +else: |
| 157 | + class CSharpIPCHandler: |
| 158 | + """C# dotnetCampus.Ipc 处理器,用于连接 ClassIsland 实例""" |
| 159 | + _instance: Optional["CSharpIPCHandler"] = None |
| 160 | + |
| 161 | + def __new__(cls): |
| 162 | + if cls._instance is None: |
| 163 | + cls._instance = super().__new__(cls) |
| 164 | + cls._instance._initialized = False |
| 165 | + return cls._instance |
| 166 | + |
| 167 | + @classmethod |
| 168 | + def instance(cls): |
| 169 | + """获取单例实例""" |
| 170 | + if cls._instance is None: |
| 171 | + cls._instance = cls() |
| 172 | + return cls._instance |
| 173 | + |
| 174 | + def __init__(self): |
| 175 | + """ |
| 176 | + 初始化 C# IPC 处理器 |
| 177 | + """ |
| 178 | + self.ipc_client = None |
| 179 | + self.client_thread = None |
| 180 | + self.is_running = False |
| 181 | + |
| 182 | + def start_ipc_client(self) -> bool: |
| 183 | + """ |
| 184 | + 启动 C# IPC 客户端 |
| 185 | +
|
| 186 | + Returns: |
| 187 | + 启动成功返回True,失败返回False |
| 188 | + """ |
| 189 | + return False |
| 190 | + |
| 191 | + def stop_ipc_client(self): |
| 192 | + """停止 C# IPC 客户端""" |
| 193 | + pass |
| 194 | + |
| 195 | + def send_notification( |
| 196 | + self, |
| 197 | + class_name, |
| 198 | + selected_students, |
| 199 | + draw_count=1, |
| 200 | + settings=None, |
| 201 | + settings_group=None |
| 202 | + ) -> bool: |
| 203 | + """发送提醒""" |
| 204 | + return False |
| 205 | + |
| 206 | + def is_breaking(self) -> bool: |
| 207 | + """是否处于下课时间""" |
| 208 | + return False |
| 209 | + |
| 210 | + @staticmethod |
| 211 | + def convert_to_call_result(class_name: str, selected_students, draw_count: int, display_duration=5.0) -> object: |
| 212 | + return object |
| 213 | + |
| 214 | + def _on_class_test(self): |
| 215 | + pass |
| 216 | + |
| 217 | + def _run_client(self): |
| 218 | + """运行 C# IPC 客户端""" |
| 219 | + pass |
0 commit comments