我气急败坏了(恼

This commit is contained in:
shenjack-5600u 2024-02-08 23:59:36 +08:00
parent 2c049bd1a5
commit 87e6864712
Signed by: shenjack
GPG Key ID: FDF9864E11C7E79F
8 changed files with 187 additions and 8 deletions

View File

@ -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"

View File

@ -0,0 +1,17 @@
{
"folders": [
{
"path": "."
},
{
"path": "../openbmclapi"
},
{
"path": "../ica-bot"
},
{
"path": "../rust-socketio"
}
],
"settings": {}
}

41
request_cert.py Normal file
View File

@ -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)

View File

@ -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<void> {
/// 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;
}
}

View File

@ -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();

View File

@ -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();
}

View File

@ -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"

View File

@ -0,0 +1,52 @@
use rust_socketio::{Payload, RawClient};
fn main() {
// 从命令行读取配置文件路径
let args: Vec<String> = std::env::args().collect();
if args.len() != 2 {
println!("Usage: {} <config file>", 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));
}