diff --git a/Cargo.toml b/Cargo.toml index 37afa63..457772b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,4 @@ +workspace = { members = ["tests/socket-test"] } [package] name = "openbmclapi_rs" version = "0.1.0" @@ -32,4 +33,4 @@ tracing = "0.1.40" tracing-subscriber = { version = "0.3.18", features = ["time"] } chrono = "0.4.33" -base64 = "0.21.7" +base64 = "0.21.7" \ No newline at end of file diff --git a/openbmclapi-rs.code-workspace b/openbmclapi-rs.code-workspace new file mode 100644 index 0000000..0e0ea23 --- /dev/null +++ b/openbmclapi-rs.code-workspace @@ -0,0 +1,17 @@ +{ + "folders": [ + { + "path": "." + }, + { + "path": "../openbmclapi" + }, + { + "path": "../ica-bot" + }, + { + "path": "../rust-socketio" + } + ], + "settings": {} +} \ No newline at end of file diff --git a/request_cert.py b/request_cert.py new file mode 100644 index 0000000..5e41df9 --- /dev/null +++ b/request_cert.py @@ -0,0 +1,41 @@ +import time + +import socketio +import tomli + +cluster_config = tomli.load(open("config.toml", "rb")) + +sio = socketio.Client() + +center = "https://openbmclapi.bangbang93.com" + +if __name__ == "__main__": + + cluster_id = cluster_config["cluster_id"] + cluster_secret = cluster_config["cluster_secret"] + """ + this.socket = connect(this.prefixUrl, { + transports: ['websocket'], + query: { + clusterId: this.clusterId, + clusterSecret: this.clusterSecret, + }, + }) + """ + + connect_url = f"{center}?clusterId={cluster_id}&clusterSecret={cluster_secret}" + sio.connect(connect_url, transports="websocket") + print("connected") + time.sleep(1) + + """ + const cert = await new Promise<{cert: string; key: string}>((resolve, reject) => { + this.socket?.emit('request-cert', ([err, cert]: [unknown, {cert: string; key: string}]) => { + if (err) return reject(err) + resolve(cert) + }) + })""" + # sio.emit("request-cert",) + sio.emit("request-cert", callback=lambda *args: print(args)) + + time.sleep(10) diff --git a/src/cluster.rs b/src/cluster.rs index 438ff14..13d53e2 100644 --- a/src/cluster.rs +++ b/src/cluster.rs @@ -13,6 +13,8 @@ use serde::Deserialize; use tracing::{debug, info, warn}; use zstd::stream::decode_all; +use std::time::Duration; + #[derive(Deserialize, Debug, Clone)] pub struct SyncFile { pub path: String, @@ -36,11 +38,18 @@ impl Cluster { .boxed() }; let ua = format!("openbmclapi-cluster/{}", PROTOCOL_VERSION); - let socket = ClientBuilder::new(config.center_url.clone()) + + // connect_url = f"{center}?clusterId={cluster_id}&clusterSecret={cluster_secret}" + let url = format!( + "{}?clusterId={}&clusterSecret={}", + config.center_url.clone(), config.cluster_id, config.cluster_secret + ); + + let socket = ClientBuilder::new(url.as_str()) .transport_type(TransportType::Websocket) - .on("error", |err, _| { - fatal!("socket error {:?}", err); - }) + .on("error", |err, _| async move { + println!("socket error {:?}", err) + }.boxed()) .on("message", |msg, _| { async move { debug!("socket message: {:?}", msg) }.boxed() }) @@ -59,6 +68,40 @@ impl Cluster { .expect("Failed to disconnect"); } + /// + /// public async requestCert(): Promise { + /// const cert = await new Promise<{cert: string; key: string}>((resolve, reject) => { + /// this.socket?.emit('request-cert', ([err, cert]: [unknown, {cert: string; key: string}]) => { + /// if (err) return reject(err) + /// resolve(cert) + /// }) + /// }) + /// await fse.outputFile(join(this.tmpDir, 'cert.pem'), cert.cert) + /// await fse.outputFile(join(this.tmpDir, 'key.pem'), cert.key) + /// } + pub async fn request_cert(&self) { + let ack_callback = |message: Payload, _| { + async move { + println!("ack_callback: {:?}", message); + match message { + Payload::Text(values) => info!("{:#?}", values), + Payload::Binary(bytes) => info!("Received bytes: {:#?}", bytes), + _ => (), + } + } + .boxed() + }; + let res = self + .socket + .emit_with_ack("request-cert", "", Duration::from_secs(10), ack_callback) + .await; + info!("request_cert res: {:?}", res); + tokio::time::sleep(Duration::from_secs(20)).await; + if res.is_err() { + warn!("request cert error: {:?}", res.err()); + } + } + /// ```typescript /// this.ua = `openbmclapi-cluster/${version}` /// this.got = got.extend({ @@ -173,5 +216,16 @@ mod tests { let cluster = Cluster::new(config).await; cluster.get_file_list().await.unwrap(); cluster.disconnect().await; + std::thread::sleep(std::time::Duration::from_secs(10)); + } + + #[cfg(feature = "local_test")] + #[tokio::test] + async fn test_get_cert() { + crate::log::init_log_with_cli(); + let config = gen_config(); + let cluster = Cluster::new(config).await; + cluster.request_cert().await; + cluster.disconnect().await; } } diff --git a/src/config.rs b/src/config.rs index fae0f2c..8322c96 100644 --- a/src/config.rs +++ b/src/config.rs @@ -62,8 +62,6 @@ impl Config { } } - pub fn raw_new() {} - pub fn convert_from_env() { // Load from env let center_url = env::var("CENTER_URL").ok(); diff --git a/src/log.rs b/src/log.rs index b65c398..9c8fb76 100644 --- a/src/log.rs +++ b/src/log.rs @@ -5,5 +5,7 @@ pub fn init_log_with_cli() { // --trace // 从低级开始判断 - tracing_subscriber::fmt::init(); + tracing_subscriber::fmt() + .with_max_level(tracing::Level::DEBUG) + .init(); } diff --git a/tests/socket-test/Cargo.toml b/tests/socket-test/Cargo.toml new file mode 100644 index 0000000..af548ad --- /dev/null +++ b/tests/socket-test/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "socket-test" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] + +rust_socketio = { path = "D:/githubs/rust-socketio/socketio", features = ["async"]} + +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0.112" +toml = "0.8.8" diff --git a/tests/socket-test/src/main.rs b/tests/socket-test/src/main.rs new file mode 100644 index 0000000..4426e67 --- /dev/null +++ b/tests/socket-test/src/main.rs @@ -0,0 +1,52 @@ +use rust_socketio::{Payload, RawClient}; + +fn main() { + // 从命令行读取配置文件路径 + let args: Vec = std::env::args().collect(); + if args.len() != 2 { + println!("Usage: {} ", args[0]); + std::process::exit(1); + } + let config_path = &args[1]; + let raw_config = std::fs::read_to_string(config_path).unwrap(); + // toml 解析 + let config: toml::Value = toml::from_str(&raw_config).unwrap(); + + let center_url = "https://openbmclapi.bangbang93.com"; + let url = format!( + "{}?clusterId={}&clusterSecret={}", + center_url, config["cluster_id"], config["cluster_secret"] + ); + + let socket = rust_socketio::ClientBuilder::new(url) + .on("connect", |args, _| { + println!("Connected: {:?}", args); + }) + .on("event", |args, _| { + println!("Event: {:?}", args); + }) + .on("disconnect", |args, _| { + println!("Disconnected: {:?}", args); + }) + .on("error", |args, _| { + println!("Error!!: {:?}", args); + }) + .connect() + .unwrap(); + + println!("Connected to server"); + let request_callback = |message: Payload, _: RawClient| { + println!("Received message: {:?}", message); + }; + + println!("Requesting cert"); + let res = socket.emit_with_ack( + "request-cert", + "", + std::time::Duration::from_secs(10), + request_callback, + ); + println!("Request result: {:?}", res); + + std::thread::sleep(std::time::Duration::from_secs(20)); +}