Merge pull request 'dev' (#1) from dev into main

Reviewed-on: #1
This commit is contained in:
Candifloss 2024-09-22 10:33:56 +00:00
commit d59e99dec3
5 changed files with 97 additions and 24 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "snot" name = "snot"
version = "0.1.0" version = "0.1.1"
edition = "2021" edition = "2021"
authors = ["candifloss <candifloss.cc>"] authors = ["candifloss <candifloss.cc>"]
@ -9,5 +9,6 @@ zbus = "4.4.0"
zvariant = "4.2.0" zvariant = "4.2.0"
tokio = { version = "1.40.0", features = ["full"] } tokio = { version = "1.40.0", features = ["full"] }
futures-util = "0.3.30" futures-util = "0.3.30"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.128" serde_json = "1.0.128"
# rson_rs = "0.2.1" rson_rs = "0.2.1"

View File

@ -8,20 +8,24 @@ Inspired by [`tiramisu`](https://github.com/Sweets/tiramisu)
- Do one thing and do it well([DOTADIW](https://en.wikipedia.org/w/index.php?title=Unix_philosophy&useskin=vector#Do_One_Thing_and_Do_It_Well)) & [KISS](https://en.wikipedia.org/wiki/KISS_Principle) principle: no extra complicated features - Do one thing and do it well([DOTADIW](https://en.wikipedia.org/w/index.php?title=Unix_philosophy&useskin=vector#Do_One_Thing_and_Do_It_Well)) & [KISS](https://en.wikipedia.org/wiki/KISS_Principle) principle: no extra complicated features
- (Not really a feature) Written in [`rust`](https://www.rust-lang.org/) using the [`zbus`](https://docs.rs/zbus/latest/zbus/) crate - (Not really a feature) Written in [`rust`](https://www.rust-lang.org/) using the [`zbus`](https://docs.rs/zbus/latest/zbus/) crate
## Upcoming feature ## Supported formats
- Better ways to work with other programs
## Currently supported formats
- Plain text - Print the output text. (✓ Just print it) - Plain text - Print the output text. (✓ Just print it)
- [`json`](https://json.org) - This output can be parsed by other programs - [`json`](https://json.org) - This output can be parsed by other programs
## Upcoming format(s)
- [`rson`](https://github.com/rson-rs/rson) - A more sensible alternative to json - [`rson`](https://github.com/rson-rs/rson) - A more sensible alternative to json
## Why? ## Upcoming feature
- Better handling of `json` and `rson` data
- Better ways to work with other programs
## Usage
```bash
snot [r|j|p] [v]
```
## Why this project?
- Something simple to work with [`EWW`](https://github.com/elkowar/eww) widgets - Something simple to work with [`EWW`](https://github.com/elkowar/eww) widgets
- I'm learning Rust - I'm learning Rust

19
src/formats/rson.rs Normal file
View File

@ -0,0 +1,19 @@
// This module deals with converting the notification object into rson format, which can be used instead of json if preferred
use crate::notification::Notification;
use rson_rs::ser::to_string as rson_string;
impl Notification {
pub fn actions_rson(&self) -> String {
if self.actions().is_empty() {
String::new()
} else {
rson_string(&self.actions()).unwrap()
}
}
pub fn hints_rson(&self) -> String {
rson_string(&self.hints()).unwrap()
}
pub fn rson(&self) -> String {
rson_string(&self).unwrap()
}
}

View File

@ -1,10 +1,12 @@
pub mod formats { pub mod formats {
pub mod json; pub mod json;
pub mod plain; pub mod plain;
pub mod rson;
} }
mod notification; mod notification;
use notification::{to_notif, Notification}; use notification::{to_notif, Notification};
use std::collections::HashMap; use std::collections::HashMap;
use std::env;
use futures_util::stream::TryStreamExt; use futures_util::stream::TryStreamExt;
use zbus::{message::Body, Connection, Result}; use zbus::{message::Body, Connection, Result};
@ -29,6 +31,19 @@ fn server_properties() -> HashMap<String, String> {
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
let op_format: &str = if args.is_empty() || args[1] == "j" {
"j" // Default value, json format
} else if args[1] == "p" {
"p" // Plain format
} else if args[1] == "r" {
"r" // rson format
} else {
"j"
};
let verbose: bool = (args.len() > 2) && (args[2] == "v");
let connection = Connection::session().await?; let connection = Connection::session().await?;
connection connection
.request_name(NOTIF_INTERFACE) // Requesting dbus for this service name. Any other services/procs using this name should be stopped/disabled before this .request_name(NOTIF_INTERFACE) // Requesting dbus for this service name. Any other services/procs using this name should be stopped/disabled before this
@ -36,6 +51,9 @@ async fn main() -> Result<()> {
let mut stream = zbus::MessageStream::from(&connection); // Convert connection to a MessageStream, yields Message items let mut stream = zbus::MessageStream::from(&connection); // Convert connection to a MessageStream, yields Message items
// Notification id, restarts with each session
let mut notification_id: u32 = 0;
// Iterate on the message stream // Iterate on the message stream
while let Some(msg) = stream.try_next().await? { while let Some(msg) = stream.try_next().await? {
// Check the method calls in the received message's header // Check the method calls in the received message's header
@ -52,9 +70,13 @@ async fn main() -> Result<()> {
let properties = server_properties(); let properties = server_properties();
// Reply with the properties // Reply with the properties
connection.reply(&msg, &properties).await?; connection.reply(&msg, &properties).await?;
if verbose {
println!("GetAll request received for interface: {interface_name}"); println!("GetAll request received for interface: {interface_name}");
}
} else { } else {
if verbose {
println!("Unknown interface requested: {interface_name}"); println!("Unknown interface requested: {interface_name}");
}
// Reply with an error // Reply with an error
connection connection
.reply_error( .reply_error(
@ -69,19 +91,23 @@ async fn main() -> Result<()> {
// Client requested server information. Respond with: (Server_name, author, software_version, dbus_spec_version) // Client requested server information. Respond with: (Server_name, author, software_version, dbus_spec_version)
let response = (SERVER_NAME, VENDOR, VERSION, SPEC_VERSION); let response = (SERVER_NAME, VENDOR, VERSION, SPEC_VERSION);
connection.reply(&msg, &response).await?; connection.reply(&msg, &response).await?;
if verbose {
println!("Request received: {member}\n\tName: {SERVER_NAME}, Vendor: {VENDOR}, Version: {VERSION}, DBus spec version: {SPEC_VERSION}"); println!("Request received: {member}\n\tName: {SERVER_NAME}, Vendor: {VENDOR}, Version: {VERSION}, DBus spec version: {SPEC_VERSION}");
// Remove this LATER // Remove this LATER
} }
}
"GetCapabilities" => { "GetCapabilities" => {
// Client requested server capabilities. Respond with the supported capabilities // Client requested server capabilities. Respond with the supported capabilities
let capabilities = vec!["actions", "body", "body-hyperlinks"]; // Add more LATER let capabilities = vec!["actions", "body", "body-hyperlinks"]; // Add more LATER
connection.reply(&msg, &capabilities).await?; connection.reply(&msg, &capabilities).await?;
if verbose {
println!("Request received: {member}\n\tCapabilities: {capabilities:?}"); println!("Request received: {member}\n\tCapabilities: {capabilities:?}");
// Remove this LATER // Remove this LATER
} }
}
"Notify" => { "Notify" => {
// New notification received. Now, respond to the client with a notification ID // New notification received. Now, respond to the client with a notification ID
let notification_id: u32 = 1; // This could be incremented or generated. DO IT LATER notification_id += 1; // This could be incremented or generated.
connection.reply(&msg, &notification_id).await?; // The client waits for this response in order to disconnect connection.reply(&msg, &notification_id).await?; // The client waits for this response in order to disconnect
// Get the body of the message // Get the body of the message
@ -90,8 +116,20 @@ async fn main() -> Result<()> {
// Convert the msg body to a Notification object // Convert the msg body to a Notification object
let notif: Notification = to_notif(&msg_body)?; let notif: Notification = to_notif(&msg_body)?;
// Handle the notif // Handle the notif
println!("New notification!\n{}\n", &notif.plain()); // Print the plain version match op_format {
println!("JSON!\n{}\n", &notif.json()); // Print the plain version "j" => {
println!("{}", &notif.json()); // Print the json version
}
"r" => {
println!("{}", &notif.rson()); // Print the plain version
}
"p" => {
println!("{}\n", &notif.plain()); // Print the plain version
}
_ => {
println!("Onkown output format.");
}
}
} }
"CloseNotification" => { "CloseNotification" => {
// Client sent a close signal. Extract notification ID of the notif to be closed from the message body // Client sent a close signal. Extract notification ID of the notif to be closed from the message body
@ -99,17 +137,21 @@ async fn main() -> Result<()> {
// Tracking notifications by their IDs, closing them, and other features may be implemented later // Tracking notifications by their IDs, closing them, and other features may be implemented later
// close_notification(notification_id); // close_notification(notification_id);
if verbose {
println!("Closing notification with ID: {notification_id}"); println!("Closing notification with ID: {notification_id}");
}
// Respond to the client, acknowledging the closure // Respond to the client, acknowledging the closure
connection.reply(&msg, &()).await?; connection.reply(&msg, &()).await?;
} }
_ => { _ => {
if verbose {
println!("Unhandled method: {member}"); // Other methods are either irrelevant or unhandled at this stage of development println!("Unhandled method: {member}"); // Other methods are either irrelevant or unhandled at this stage of development
} }
} }
} }
} }
}
Ok(()) Ok(())
} }

View File

@ -1,10 +1,10 @@
// use serde::Serialize; use serde::Serialize;
use std::collections::HashMap; use std::collections::HashMap;
use zbus::{message::Body, Result}; use zbus::{message::Body, Result};
use zvariant::OwnedValue; use zvariant::OwnedValue;
// A notificaion object // A notificaion object
// #[derive(Serialize)] // To help with json #[derive(Serialize)] // To help with json, rson
pub struct Notification { pub struct Notification {
// The application that sent the notification // The application that sent the notification
app_name: String, app_name: String,
@ -65,6 +65,13 @@ impl Notification {
} }
actions actions
} }
/*
pub fn actions(&self) -> Vec<(String, String)> {
self.actions
.chunks(2)
.map(|chunk| (chunk[0].clone(), chunk[1].clone()))
.collect()
} */
// Hints // Hints
pub fn hints(&self) -> &HashMap<String, OwnedValue> { pub fn hints(&self) -> &HashMap<String, OwnedValue> {