This commit is contained in:
shenjack 2024-02-22 14:10:11 +08:00
parent 75e7e0085a
commit df0355cad7
Signed by: shenjack
GPG Key ID: 7B1134A979775551
7 changed files with 96 additions and 45 deletions

View File

@ -1,6 +1,6 @@
[package]
name = "ica-rs"
version = "0.4.3"
version = "0.4.4"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -60,7 +60,11 @@ class NewMessage:
class IcaClient:
@staticmethod
async def send_message_a(client: "IcaClient", message: SendMessage) -> bool:
...
"""
仅作占位
(因为目前来说, rust调用 Python端没法启动一个异步运行时
所以只能 tokio::task::block_in_place 转换成同步调用)
"""
def send_message(self, message: SendMessage) -> bool:
...
def debug(self, message: str) -> None:

View File

@ -137,7 +137,6 @@ pub async fn connect_callback(payload: Payload, _client: Client) {
if let Some(value) = values.first() {
match value.as_str() {
Some("authSucceed") => {
py::run();
info!("{}", "已经登录到 icalingua!".green())
}
Some("authFailed") => {

View File

@ -195,33 +195,22 @@ pub struct IcaClientPy {
#[pymethods]
impl IcaClientPy {
// fn send_message(&self, message: SendMessagePy) -> bool {
// // Some(send_message(&self.client, &message.msg).await)
// true
// // // Ok(send_message(&self.client, &message.msg).await)
// // let mut future;
// // Python::with_gil(|gil| {
// // let this = self_.borrow(gil);
// // future = send_message(&this.client, &message.msg);
// // });
// // Ok(future.await)
// }
pub fn send_message(&self, message: SendMessagePy) -> bool {
// let handle = tokio::runtime::Handle::current();
// handle.block_on(send_message(&self.client, &message.msg))
tokio::task::block_in_place(|| {
let rt = Runtime::new().unwrap();
rt.block_on(send_message(&self.client, &message.msg))
})
}
/// 仅作占位
/// (因为目前来说, rust调用 Python端没法启动一个异步运行时
/// 所以只能 tokio::task::block_in_place 转换成同步调用)
#[staticmethod]
pub fn send_message_a(
py: Python,
client: IcaClientPy,
message: SendMessagePy,
) -> PyResult<&PyAny> {
// send_message(&client.client, &message.msg).await
pyo3_asyncio::tokio::future_into_py(py, async move {
Ok(send_message(&client.client, &message.msg).await)
})

View File

@ -34,8 +34,10 @@ impl PyStatus {
match PYSTATUS.files.as_mut() {
Some(files) => {
files.insert(path, (changed_time, py_module));
debug!("Added file to py status, {:?}", files);
}
None => {
warn!("No files in py status, creating new");
let mut files = HashMap::new();
files.insert(path, (changed_time, py_module));
PYSTATUS.files = Some(files);
@ -44,11 +46,20 @@ impl PyStatus {
}
}
pub fn verify_file(path: &PathBuf, change_time: &Option<SystemTime>) -> bool {
pub fn verify_file(path: &PathBuf) -> bool {
unsafe {
match PYSTATUS.files.as_ref() {
Some(files) => match files.get(path) {
Some((changed_time, _)) => change_time == changed_time,
Some((changed_time, _)) => {
if let Some(changed_time) = changed_time {
if let Some(new_changed_time) = get_change_time(path) {
if new_changed_time != *changed_time {
return false;
}
}
}
true
},
None => false,
},
None => false,
@ -59,21 +70,6 @@ impl PyStatus {
pub static mut PYSTATUS: PyStatus = PyStatus { files: None };
pub fn run() {
Python::with_gil(|py| {
let bot_status = class::IcaStatusPy::new();
let _bot_status: &PyCell<_> = PyCell::new(py, bot_status).unwrap();
let locals = [("state", _bot_status)].into_py_dict(py);
py.run(
"from pathlib import Path\nprint(Path.cwd())\nprint(state)",
None,
Some(locals),
)
.unwrap();
});
}
pub fn load_py_plugins(path: &PathBuf) {
if path.exists() {
info!("finding plugins in: {:?}", path);
@ -90,18 +86,25 @@ pub fn load_py_plugins(path: &PathBuf) {
if ext == "py" {
match load_py_file(&path) {
Ok((changed_time, content)) => {
let py_module = Python::with_gil(|py| -> Py<PyAny> {
let module: Py<PyAny> = PyModule::from_code(
let py_module: PyResult<Py<PyAny>> = Python::with_gil(|py| -> PyResult<Py<PyAny>> {
let module: PyResult<Py<PyAny>> = PyModule::from_code(
py,
&content,
&path.to_string_lossy(),
"",
&path.to_string_lossy()
)
.unwrap()
.into();
.map(|module| module.into());
module
});
PyStatus::add_file(path, changed_time, py_module);
match py_module {
Ok(py_module) => {
info!("加载到插件: {:?}", path);
PyStatus::add_file(path, changed_time, py_module);
}
Err(e) => {
warn!("failed to load file: {:?} | e: {:?}", path, e);
}
}
}
Err(e) => {
warn!("failed to load file: {:?} | e: {:?}", path, e);
@ -123,6 +126,31 @@ pub fn load_py_plugins(path: &PathBuf) {
);
}
pub fn verify_plugins() {
let plugins = PyStatus::get_files();
for (path, _) in plugins.iter() {
if !PyStatus::verify_file(path) {
info!("file changed: {:?}", path);
if let Ok((changed_time, content)) = load_py_file(path) {
let py_module = Python::with_gil(|py| -> Py<PyAny> {
let module: Py<PyAny> = PyModule::from_code(
py,
&content,
&path.to_string_lossy(),
&path.to_string_lossy(),
// !!!! 请注意, 一定要给他一个名字, cpython 会自动把后面的重名模块覆盖掉前面的
)
.unwrap()
.into();
module
});
PyStatus::add_file(path.clone(), changed_time, py_module);
}
}
}
}
pub fn get_change_time(path: &PathBuf) -> Option<SystemTime> {
path.metadata().ok()?.modified().ok()
}
@ -149,13 +177,20 @@ pub fn init_py(config: &IcaConfig) {
/// 执行 new message 的 python 插件
pub async fn new_message_py(message: &NewMessage, client: &Client) {
// 验证插件是否改变
verify_plugins();
let cwd = std::env::current_dir().unwrap();
let plugins = PyStatus::get_files();
for (path, (_, py_module)) in plugins.iter() {
// 切换工作目录到运行的插件的位置
if let Err(e) = std::env::set_current_dir(path.parent().unwrap()) {
warn!("failed to set current dir: {:?}", e);
let mut goto = cwd.clone();
goto.push(path.parent().unwrap());
if let Err(e) = std::env::set_current_dir(&goto) {
warn!("移动工作目录到 {:?} 失败 {:?} cwd: {:?}", goto, e, cwd);
}
Python::with_gil(|py| {
let msg = class::NewMessagePy::new(message);
let client = class::IcaClientPy::new(client);
@ -171,8 +206,9 @@ pub async fn new_message_py(message: &NewMessage, client: &Client) {
}
});
}
// 最后切换回来
if let Err(e) = std::env::set_current_dir(cwd) {
warn!("failed to set current dir: {:?}", e);
if let Err(e) = std::env::set_current_dir(&cwd) {
warn!("设置工作目录{:?} 失败:{:?}", cwd, e);
}
}

View File

@ -1,5 +1,10 @@
# 更新日志
## 0.4.4
现在正式支持 Python 插件了
`/bmcl` 也迁移到了 Python 插件版本
## 0.4.3
噫! 好! 我成了!

View File

@ -5,7 +5,7 @@
> 出于某个企鹅, 和保护 作者 和 原项目 ( ica ) 的原因 \
> 功能请自行理解
## 使用方法
## 使用方法 ( Python 版 )
- 安装依赖
@ -40,3 +40,21 @@ docker up -d
```powershell
python connect.py
```
## 使用方法 ( Rust 版 )
- 准备一个 Python 环境
- 修改好配置文件
```powershell
Copy-Item config-temp.toml config.toml
```
- 编译
```powershell
cargo build --release
```
运行