|
| 1 | +use byteorder::WriteBytesExt; |
| 2 | +use futures::stream::Stream; |
| 3 | +use interprocess::local_socket::tokio::Stream as InterprocessTokioStream; |
| 4 | +use interprocess::local_socket::traits::Stream as InterprocessStreamTrait; |
| 5 | +use interprocess::local_socket::traits::tokio::Listener as TokioListener; |
| 6 | +use interprocess::local_socket::{GenericNamespaced, ListenerOptions, ToNsName}; |
| 7 | +use interprocess::local_socket::{Name, Stream as InterprocessStream}; |
| 8 | + |
| 9 | +use tokio::io::AsyncReadExt; |
| 10 | + |
| 11 | +#[derive(Debug, Clone)] |
| 12 | +pub enum IpcEvent { |
| 13 | + Show, |
| 14 | +} |
| 15 | + |
| 16 | +impl TryFrom<u8> for IpcEvent { |
| 17 | + type Error = (); |
| 18 | + |
| 19 | + fn try_from(value: u8) -> Result<Self, Self::Error> { |
| 20 | + match value { |
| 21 | + 0 => Ok(IpcEvent::Show), |
| 22 | + _ => Err(()), |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +impl From<IpcEvent> for u8 { |
| 28 | + fn from(value: IpcEvent) -> Self { |
| 29 | + match value { |
| 30 | + IpcEvent::Show => 0, |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +fn get_name() -> anyhow::Result<Name<'static>> { |
| 36 | + let printname = "android-mic.sock"; |
| 37 | + let name = printname.to_ns_name::<GenericNamespaced>()?; |
| 38 | + Ok(name) |
| 39 | +} |
| 40 | + |
| 41 | +pub async fn create_stream() -> anyhow::Result<InterprocessTokioStream> { |
| 42 | + let name = get_name()?; |
| 43 | + |
| 44 | + let opts = ListenerOptions::new().name(name); |
| 45 | + |
| 46 | + let listener = opts.create_tokio()?; |
| 47 | + |
| 48 | + let stream = listener.accept().await?; |
| 49 | + Ok(stream) |
| 50 | +} |
| 51 | + |
| 52 | +pub fn parse_stream(stream: InterprocessTokioStream) -> impl Stream<Item = IpcEvent> { |
| 53 | + futures::stream::unfold(stream, |mut stream| async { |
| 54 | + match stream.read_u8().await { |
| 55 | + Ok(value) => match value.try_into() { |
| 56 | + Ok(event) => Some((event, stream)), |
| 57 | + Err(()) => { |
| 58 | + error!("can't parse ipc event"); |
| 59 | + None |
| 60 | + } |
| 61 | + }, |
| 62 | + Err(e) => { |
| 63 | + error!("{e}"); |
| 64 | + None |
| 65 | + } |
| 66 | + } |
| 67 | + }) |
| 68 | +} |
| 69 | + |
| 70 | +pub fn send_event(event: IpcEvent) -> anyhow::Result<()> { |
| 71 | + let name = get_name()?; |
| 72 | + |
| 73 | + let mut stream = InterprocessStream::connect(name)?; |
| 74 | + |
| 75 | + stream.write_u8(event.into())?; |
| 76 | + |
| 77 | + Ok(()) |
| 78 | +} |
0 commit comments