Compare commits

..

17 Commits
v0.1.0 ... main

Author SHA1 Message Date
78a84f4b48 Merge pull request 'dev' (#2) from dev into main
Reviewed-on: #2
2024-09-27 10:06:26 +00:00
f568ac111d error handling 2024-09-27 15:29:14 +05:30
4dfa6e4d3d error handling 2024-09-27 12:16:31 +05:30
a6b95bad57 option fixes 2024-09-27 00:51:37 +05:30
5bcddfbad9 edit README 2024-09-26 16:27:48 +05:30
e83a14dac4 edited README 2024-09-26 16:26:07 +05:30
4a708bb6a0 fixed option parsing 2024-09-26 16:16:46 +05:30
05833c5d99 options parsing 2024-09-26 13:37:39 +05:30
8c373462aa removed comment 2024-09-25 13:18:52 +05:30
b572fa1cc2 commit 2024-09-24 14:01:11 +05:30
9dd8b12faf Changed json and rson format generation 2024-09-23 20:27:43 +05:30
ca9499db5f Merge pull request 'dev' (#1) from dev into main
Reviewed-on: #1
2024-09-22 10:33:56 +00:00
16cc772475 edited README 2024-09-22 15:57:03 +05:30
6fe5d22745 Got rson working, added format and verbose options 2024-09-22 15:48:27 +05:30
3b92de541a Added options j/p 2024-09-22 11:16:51 +05:30
04db8a6454 begin rson.rs 2024-09-22 01:32:17 +05:30
c7c07d0024 Update README.md 2024-09-21 19:55:17 +00:00
8 changed files with 171 additions and 101 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,7 @@ 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.210", features = ["derive"] }
serde_json = "1.0.128" serde_json = "1.0.128"
# rson_rs = "0.2.1" rson_rs = "0.2.1"
argh = "0.1.12"

View File

@ -8,15 +8,32 @@ 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 ## Usage
- Better ways to work with other programs ```bash
snot --help
Usage: snot [-f <format>] [-v]
## Currently supported formats Print desktop notifications
Options:
-f, --format select output format: r(rson), j(json, default), p(plain)
-v, --verbose verbose mode
--help display usage information
```
## 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
## Upcoming feature
- Better handling of `json` and `rson` data
- Better ways to work with other programs
## Why this project?
- Something simple to work with [`EWW`](https://github.com/elkowar/eww) widgets
- I'm learning Rust

View File

@ -3,68 +3,7 @@ use crate::notification::Notification;
use serde_json::{json, Value}; // json!() macro and Value type use serde_json::{json, Value}; // json!() macro and Value type
impl Notification { impl Notification {
// Actions, as json
pub fn actions_json(&self) -> Value {
if self.actions().is_empty() {
json!({}) // Empty JSON object if no actions
} else {
serde_json::Value::Object(
// Wrap the map into a serde_json::Value
self.actions()
.iter()
.map(|(id, label)| {
(id.clone(), json!(label)) // Create key-value pairs: id -> label
})
.collect::<serde_json::Map<_, _>>(), // Collect into a serde_json::Map
)
}
}
// Default action, as json string
pub fn default_action_json(&self) -> Value {
match self.default_action() {
None => serde_json::Value::from("None"),
Some(actn) => serde_json::Value::String(actn.0),
}
}
// Hints, as json
pub fn hints_json(&self) -> Value {
if self.hints().is_empty() {
json!({}) // Empty JSON object if no hints
} else {
serde_json::Value::Object(
self.hints()
.iter()
.map(|(key, value)| {
(key.clone(), json!(value.to_string())) // Convert hint value to string
})
.collect::<serde_json::Map<_, _>>(), // Collect into a serde_json::Map
)
}
}
// The notification as a json object
pub fn json(&self) -> Value { pub fn json(&self) -> Value {
// Initialize json!(self)
let mut notif_json: Value = json!({
"app_name": &self.app_name(),
"replace_id": &self.replace_id(),
"icon": &self.icon(),
"summary": &self.summary(),
"body": &self.body(),
"hints": &self.hints_json(),
"expiration_timeout": self.expir_timeout(),
"urgency": self.urgency(),
});
// Conditionally add the Actions fields
if let Value::Object(ref mut map) = notif_json {
if !self.actions().is_empty() {
map.insert("actions".to_string(), self.actions_json());
map.insert("default_action".to_string(), self.default_action_json());
}
}
notif_json
} }
} }

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

@ -0,0 +1,10 @@
// 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;
use rson_rs::de::Error as RsonError;
impl Notification {
pub fn rson(&self) -> Result<String, RsonError> {
rson_string(self).map_err(|e| RsonError::Message(format!("RSON serialization error: {}", e)))
}
}

41
src/formats/serde.rs Normal file
View File

@ -0,0 +1,41 @@
use serde::{Serialize, Serializer};
/*
use std::collections::HashMap;
use std::hash::BuildHasher;
use zvariant::OwnedValue; */
pub fn serialize_actions<S>(actions: &[String], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serde_json::Map::new();
// Assuming actions are in pairs: [id, label, id, label, ...]
for chunk in actions.chunks(2) {
if let [id, label] = chunk {
map.insert(id.clone(), serde_json::Value::String(label.clone()));
}
}
map.serialize(serializer)
}
/*
pub fn serialize_hints<S, H>(
hints: &HashMap<String, OwnedValue, H>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
H: BuildHasher,
{
let mut map = serde_json::Map::new();
for (key, value) in hints {
// Customize OwnedValue serialization as needed
map.insert(key.clone(), serde_json::Value::String(value.to_string()));
}
map.serialize(serializer)
}
*/

View File

@ -1,17 +1,20 @@
pub mod formats { pub mod formats {
pub mod json; pub mod json;
pub mod plain; pub mod plain;
pub mod rson;
pub mod serde;
} }
mod notification; mod notification;
use notification::{to_notif, Notification}; use notification::{to_notif, Notification};
use std::collections::HashMap; use std::collections::HashMap;
pub mod optparse;
use futures_util::stream::TryStreamExt; use futures_util::stream::TryStreamExt;
use zbus::{message::Body, Connection, Result}; use zbus::{message::Body, Connection, Result};
const SERVER_NAME: &str = "SNot"; // Server software name const SERVER_NAME: &str = "SNot"; // Server software name
const VENDOR: &str = "candifloss.cc"; // Server software vendor const VENDOR: &str = "candifloss.cc"; // Server software vendor
const VERSION: &str = "0.1.0"; // Server software version const VERSION: &str = "0.1.2"; // Server software version
const SPEC_VERSION: &str = "0.42"; // DBus specification version const SPEC_VERSION: &str = "0.42"; // DBus specification version
const NOTIF_INTERFACE: &str = "org.freedesktop.Notifications"; // DBus interface name const NOTIF_INTERFACE: &str = "org.freedesktop.Notifications"; // DBus interface name
@ -29,6 +32,29 @@ fn server_properties() -> HashMap<String, String> {
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
// Options
let args: optparse::Cli = argh::from_env();
// Format: r|j|p
let op_format = match args.format {
Some(value) => {
// Reject invalid format option
if ["r", "j", "p"].contains(&value.as_str()) {
value.clone()
} else {
// Exit with error code
return Err(zbus::Error::from(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Invalid output format",
)));
}
}
None => "j".to_string(),
};
// Verbose mode. Off/false by default
let verbose = args.verbose;
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 +62,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 +81,10 @@ 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?;
println!("GetAll request received for interface: {interface_name}"); if verbose {
println!("GetAll request received for interface: {interface_name}");
}
} else { } else {
println!("Unknown interface requested: {interface_name}");
// Reply with an error // Reply with an error
connection connection
.reply_error( .reply_error(
@ -63,25 +93,32 @@ async fn main() -> Result<()> {
&"Unknown interface".to_string(), &"Unknown interface".to_string(),
) )
.await?; .await?;
if verbose {
println!("Unknown interface requested: {interface_name}");
}
} }
} }
"GetServerInformation" => { "GetServerInformation" => {
// 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?;
println!("Request received: {member}\n\tName: {SERVER_NAME}, Vendor: {VENDOR}, Version: {VERSION}, DBus spec version: {SPEC_VERSION}"); if verbose {
// Remove this LATER println!("Request received: {member}\n\tName: {SERVER_NAME}, Vendor: {VENDOR}, Version: {VERSION}, DBus spec version: {SPEC_VERSION}");
// 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?;
println!("Request received: {member}\n\tCapabilities: {capabilities:?}"); if verbose {
// Remove this LATER println!("Request received: {member}\n\tCapabilities: {capabilities:?}");
// 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,22 +127,42 @@ 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.as_str() {
println!("JSON!\n{}\n", &notif.json()); // Print the plain version "j" => {
println!("{}", &notif.json()); // Print the json version
}
"r" => {
// Print the rson version
match notif.rson() {
Ok(rson_string) => println!("{}", rson_string),
Err(e) => eprintln!("Failed to convert to RSON: {}", e),
}
}
"p" => {
println!("{}\n", &notif.plain()); // Print the plain version
}
_ => {
println!("Onkown output format."); // This is probably unreachable
}
}
} }
"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
let notification_id: u32 = msg.body().deserialize()?; // This method has only one parameter, the id let notification_id: u32 = msg.body().deserialize()?; // This method has only one parameter, the id
// 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);
println!("Closing notification with ID: {notification_id}"); if verbose {
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?;
} }
_ => { _ => {
println!("Unhandled method: {member}"); // Other methods are either irrelevant or unhandled at this stage of development if verbose {
println!("Unhandled method: {member}"); // Other methods are either irrelevant or unhandled at this stage of development
}
} }
} }
} }

View File

@ -1,10 +1,11 @@
// use serde::Serialize; use crate::formats::serde::serialize_actions;
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,
@ -17,8 +18,10 @@ pub struct Notification {
// Notification content/body // Notification content/body
body: String, body: String,
// Action requests that can be sent back to the client - "Reply," "Mark as Read," "Play/Pause/Next," "Snooze/Dismiss," etc. // Action requests that can be sent back to the client - "Reply," "Mark as Read," "Play/Pause/Next," "Snooze/Dismiss," etc.
#[serde(serialize_with = "serialize_actions")]
actions: Vec<String>, actions: Vec<String>,
// Useful extra data - notif type, urgency, notif sound, icon data, etc. // Useful extra data - notif type, urgency, notif sound, icon data, etc.
//#[serde(serialize_with = "serialize_hints")]
hints: HashMap<String, OwnedValue>, hints: HashMap<String, OwnedValue>,
// Seconds till this notif expires. Optional // Seconds till this notif expires. Optional
expir_timeout: i32, expir_timeout: i32,
@ -48,22 +51,10 @@ impl Notification {
// Key:Val pairs of actions // Key:Val pairs of actions
pub fn actions(&self) -> Vec<(String, String)> { pub fn actions(&self) -> Vec<(String, String)> {
let mut actions: Vec<(String, String)> = vec![]; self.actions
let acts = &self.actions; .chunks(2)
let act_len = acts.len(); .map(|chunk| (chunk[0].clone(), chunk[1].clone()))
let mut i = 0; .collect()
while i < act_len {
// Action ID, used by the sender to id the clicked action
let action_id = &acts[i];
// Localised human-readable string that describes the action
let action_label = &acts[i + 1];
// Pair of (id, label)
let action_pair = (action_id.to_owned(), action_label.to_owned());
// Add it to the Vec
actions.push(action_pair);
i += 2;
}
actions
} }
// Hints // Hints

13
src/optparse.rs Normal file
View File

@ -0,0 +1,13 @@
use argh::FromArgs;
#[derive(FromArgs)]
/// Print desktop notifications
pub struct Cli {
/// select output format: r(rson), j(json, default), p(plain)
#[argh(option, short = 'f')]
pub format: Option<String>,
/// verbose mode
#[argh(switch, short = 'v')]
pub verbose: bool,
}