1. 完善code,新建线程监听ok,sub msg的格式确定。待完善code

This commit is contained in:
Ekko.bao 2024-08-08 08:50:10 +08:00
parent 295b866cf4
commit ef5ba10d0e
2 changed files with 95 additions and 27 deletions

View File

@ -4,7 +4,12 @@ use reqwest::{Client, Response};
use scraper::{Html, Selector}; use scraper::{Html, Selector};
use std::error::Error; use std::error::Error;
use std::io; use std::io;
use std::thread; use std::ops::Index;
use std::time::Duration;
use tokio::sync::{Mutex};
use std::sync::Arc;
use tokio::{task, time};
use std::collections::{BTreeMap, VecDeque};
extern crate log; extern crate log;
pub mod wclip; pub mod wclip;
@ -27,6 +32,23 @@ pub struct ClipboardMsgs {
pub msgs: Vec<String>, pub msgs: Vec<String>,
} }
async fn msg_sync(ctx:Arc<Mutex<ClipboardSync>>){
let mut ctx = ctx.lock().await;
loop{
let _ = ctx.update_msg().await;
time::sleep(Duration::new(10, 0)).await;
}
}
pub async fn start_msg_sync(ctx:Arc<Mutex<ClipboardSync>>) -> Result<task::JoinHandle<()>, Box<dyn Error>>{
let handle = task::spawn(msg_sync(ctx));
Ok(handle)
}
enum Msg <'a>{
Msg(&'a str),
Sub((i8, i8, i8, &'a str)),
}
impl ClipboardSync { impl ClipboardSync {
pub fn new(ip: &str, user_name: &str, password: &str) -> ClipboardSync { pub fn new(ip: &str, user_name: &str, password: &str) -> ClipboardSync {
ClipboardSync { ClipboardSync {
@ -39,20 +61,6 @@ impl ClipboardSync {
} }
} }
pub async fn run(&mut self) Result<(), Box<dyn Error>>{
self.login()?;
let arctx = Arc::new(Mutex::new(self));
let ctx = arctx.clone();
let handle = thread::spawn(move || {
let mut ctx = ctx.lock().unwrap()
loop{
ctx.update_msg().await;
}
})
thread::join(handle).unwrap();
Ok(())
}
async fn verify(&self) -> Result<Response, Box<dyn Error>> { async fn verify(&self) -> Result<Response, Box<dyn Error>> {
// 开始验证 // 开始验证
@ -124,14 +132,14 @@ impl ClipboardSync {
log::trace!("verify Response: {}", resp); log::trace!("verify Response: {}", resp);
} }
if resp.contains("<title>Copy & Paste</title>") { if resp.contains("<title>Copy & Paste</title>") {
self.parse_msg(&resp).await; self.msg2clip(&resp).await;
Ok(()) Ok(())
} else { } else {
Err(Box::new(io::Error::new(io::ErrorKind::Other, "登录失败"))) Err(Box::new(io::Error::new(io::ErrorKind::Other, "登录失败")))
} }
} }
pub asyn fn update_msg(&mut self) -> Result<(), Box<dyn Error>> { pub async fn update_msg(&mut self) -> Result<(), Box<dyn Error>> {
//http://ssweb/SSWeb/rd/copy_paste.jsp?d-16544-p=1&d-16544-s=2 //http://ssweb/SSWeb/rd/copy_paste.jsp?d-16544-p=1&d-16544-s=2
//d-16544-s 2:时间从靠近现在开始排序 1:时间从最早开始排序 //d-16544-s 2:时间从靠近现在开始排序 1:时间从最早开始排序
//d-16544-o mesage排序不要设置 //d-16544-o mesage排序不要设置
@ -149,26 +157,81 @@ impl ClipboardSync {
headers.insert("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6".parse().unwrap()); headers.insert("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6".parse().unwrap());
let response = self.web.get(url).headers(headers).send().await?; let response = self.web.get(url).headers(headers).send().await?;
let resp = response.text().await?; let resp = response.text().await?;
self.parse_msg(&resp).await; self.msg2clip(&resp).await;
Ok(()) Ok(())
} }
fn parse_msg<'a>(msg: &'a str) -> Msg {
//x|x|x| -> index|total|magic|
let head = &msg[0..7];
let body = &msg[7..];
let text = head.split('|').collect::<Vec<_>>();
if text.len() == 3 && text[0].len() == 1 && text[1].len() == 1 && text[2].len() == 1{
pub async fn parse_msg(&mut self, html: &str) -> Result<ClipboardMsgs, Box<dyn Error>> { let check = head.split('|').filter(|text| {
let text = text.as_bytes();
if text.len() == 1 {
let text = text[0] as i8;
if text < '!' as i8 && text >= '|' as i8 {
true
} else {
false
}
} else {
false
}
}).collect::<Vec<&str>>();
let index = text[0].as_bytes()[0] as i8;
if index < '!' as i8 && index >= '|' as i8 {
return Msg::Msg(msg)
}
let total = text[1].as_bytes()[1] as i8;
if total < '!' as i8 && total >= '|' as i8 {
return Msg::Msg(msg)
}
let magic = text[2].as_bytes()[1] as i8;
if magic < '!' as i8 && magic >= '|' as i8 {
return Msg::Msg(msg)
}
return Msg::Sub((index, total, magic, body));
}
return Msg::Msg(msg)
}
pub async fn msg2clip(&mut self, html: &str) {
// log::info!("html: {}", html); // log::info!("html: {}", html);
let document = Html::parse_document(html); let document = Html::parse_document(html);
let selector = Selector::parse("code").unwrap(); let selector = Selector::parse("code").unwrap();
for element in document.select(&selector) { let mut clip_text = String::new();
let mut msg_map = BTreeMap::new();
let mut magic_ref = 0;
for element in document.select(&selector).into_iter() {
//let text = element.text().collect::<Vec<_>>().concat(); //let text = element.text().collect::<Vec<_>>().concat();
let text = element.text().collect::<String>(); let text = element.text().collect::<String>();
log::info!("Found: [{}]", text); log::info!("Found: [{}]", text);
if text[0] == '@' && text[6] == '@' { let msg = ClipboardSync::parse_msg(text.as_str());
items = text.split('@').map(|x| x.trim()).collect::<Vec<_>>(); match msg {
index = items.next(); Msg::Msg(msg) => {
index = items.next(); if magic_ref == 0 {
self.clip.set(&msg);
break;
}
},
Msg::Sub((index, total, magic, body)) => {
if magic_ref == 0{
magic_ref = magic;
} else if magic_ref == magic {
msg_map.insert(index, element);
if msg_map.len() == (total - 'a' as i8) as usize {
}
// clip_text.push_str(body);
} else {
break;
}
}
} }
self.clip.set(&text);
break;
} }
Ok(ClipboardMsgs { msgs: vec![] }) if clip_text.len() != 0 {
self.clip.set(&clip_text);
}
} }
} }

View File

@ -5,6 +5,8 @@ use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts}, config::{ResolverConfig, ResolverOpts},
Resolver, Resolver,
}; };
use tokio::sync::{Mutex};
use std::sync::Arc;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
@ -35,6 +37,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
log::error!("登录失败: {}", e); log::error!("登录失败: {}", e);
} }
} }
let ctx = Arc::new(Mutex::new(ins));
let handle = clipboard_sync::start_msg_sync(ctx.clone()).await.unwrap();
let _ = handle.await;
// 获取 Cookies // 获取 Cookies
//if let Some(cookies) = response.headers().get(COOKIE) { //if let Some(cookies) = response.headers().get(COOKIE) {
// println!("Cookies: {:?}", cookies); // println!("Cookies: {:?}", cookies);