Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ path = "src/main.rs"
[dependencies]
clap = { version = "4.6", features = ["derive"] }
reqwest = { version = "0.13", default-features = false, features = ["json", "query", "rustls", "webpki-roots"] }
tokio = { version = "1.52", features = ["macros", "rt-multi-thread"] }
tokio = { version = "1.52", features = ["macros", "rt-multi-thread", "fs"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"
colored = "3.1"
comfy-table = "7.2"
futures = "0.3"
base64 = "0.22"
mime_guess = "2.0"

[profile.release]
strip = true
Expand Down
31 changes: 25 additions & 6 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use anyhow::{anyhow, Context, Result};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
use reqwest::{Client, Method, Response, StatusCode};
use serde::Serialize;
use serde_json::Value;

use crate::config::Config;

const UA: &str = concat!("zammad-cli/", env!("CARGO_PKG_VERSION"));

pub struct ZammadClient {
http: Client,
base_url: String,
Expand All @@ -20,6 +22,8 @@ impl ZammadClient {
HeaderValue::from_str(&auth).context("Invalid token characters")?,
);
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
// Explicit UA — bypasses Cloudflare WAF default-UA blocks (error 1010)
headers.insert(USER_AGENT, HeaderValue::from_static(UA));
let http = Client::builder()
.default_headers(headers)
.timeout(std::time::Duration::from_secs(30))
Expand Down Expand Up @@ -61,6 +65,15 @@ impl ZammadClient {
pub async fn put<B: Serialize + ?Sized>(&self, path: &str, body: Option<&B>) -> Result<Value> {
self.request::<(), B>(Method::PUT, path, None, body).await
}

pub async fn delete<B: Serialize + ?Sized>(
&self,
path: &str,
body: Option<&B>,
) -> Result<Value> {
self.request::<(), B>(Method::DELETE, path, None, body)
.await
}
}

async fn handle_response(resp: Response) -> Result<Value> {
Expand All @@ -77,15 +90,17 @@ async fn handle_response(resp: Response) -> Result<Value> {
}

let body = resp.text().await.unwrap_or_default();
let msg = serde_json::from_str::<Value>(&body)
.ok()
let parsed = serde_json::from_str::<Value>(&body).ok();
let msg = parsed
.as_ref()
.and_then(|v| {
v.get("error")
v.get("error_human")
.or_else(|| v.get("error"))
.or_else(|| v.get("message"))
.and_then(|m| m.as_str())
.map(|s| s.to_string())
})
.unwrap_or(body);
.unwrap_or_else(|| body.clone());

let prefix = match status {
StatusCode::NOT_FOUND => "Not found (404)",
Expand All @@ -95,5 +110,9 @@ async fn handle_response(resp: Response) -> Result<Value> {
StatusCode::UNPROCESSABLE_ENTITY => "Unprocessable (422)",
_ => "Zammad API error",
};
Err(anyhow!("{prefix}: {msg}"))
if !body.is_empty() && body.trim() != msg.trim() {
Err(anyhow!("{prefix}: {msg}\n--- raw: {body}"))
} else {
Err(anyhow!("{prefix}: {msg}"))
}
}
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod org;
pub mod system;
pub mod tags;
pub mod ticket;
pub mod user;
113 changes: 113 additions & 0 deletions src/commands/tags.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use anyhow::Result;
use clap::Subcommand;

use crate::client::ZammadClient;
use crate::output;

pub const TICKET_OBJECT: &str = "Ticket";

#[derive(Subcommand)]
pub enum TagsCmd {
/// List tags attached to an object (e.g. `tags list --object Ticket --id 42`)
List {
#[arg(long, default_value = TICKET_OBJECT)]
object: String,
#[arg(long)]
id: i64,
},
/// Add a tag to an object
Add {
#[arg(long, default_value = TICKET_OBJECT)]
object: String,
#[arg(long)]
id: i64,
#[arg(long)]
name: String,
},
/// Remove a tag from an object
Remove {
#[arg(long, default_value = TICKET_OBJECT)]
object: String,
#[arg(long)]
id: i64,
#[arg(long)]
name: String,
},
}

pub async fn run(cmd: TagsCmd, client: &ZammadClient, json: bool) -> Result<()> {
match cmd {
TagsCmd::List { object, id } => list(client, &object, id, json).await,
TagsCmd::Add { object, id, name } => {
tag_op(client, "add", &object, id, &name).await?;
if json {
output::emit_value(&serde_json::json!({"ok": true, "op": "add", "tag": name}))
} else {
output::print_message(&format!("Tag '{name}' added on {object} #{id}"));
Ok(())
}
}
TagsCmd::Remove { object, id, name } => {
tag_op(client, "remove", &object, id, &name).await?;
if json {
output::emit_value(&serde_json::json!({"ok": true, "op": "remove", "tag": name}))
} else {
output::print_message(&format!("Tag '{name}' removed on {object} #{id}"));
Ok(())
}
}
}
}

/// Single tag add/remove call. Zammad takes one `item` per request and
/// requires DELETE (not POST) for `/tags/remove`.
pub async fn tag_op(
client: &ZammadClient,
op: &str,
object: &str,
id: i64,
name: &str,
) -> Result<()> {
let path = format!("/api/v1/tags/{op}");
let payload = serde_json::json!({
"object": object,
"o_id": id,
"item": name,
});
match op {
"add" => {
client.post(&path, Some(&payload)).await?;
}
"remove" => {
client.delete(&path, Some(&payload)).await?;
}
_ => anyhow::bail!("Unknown tag op: {op}"),
}
Ok(())
}

async fn list(client: &ZammadClient, object: &str, id: i64, json: bool) -> Result<()> {
let params = vec![("object", object.to_string()), ("o_id", id.to_string())];
let value = client.get("/api/v1/tags", Some(&params)).await?;
if json {
return output::emit_value(&value);
}
let tags = value
.get("tags")
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|t| t.as_str().map(|s| s.to_string()))
.collect::<Vec<_>>()
})
.unwrap_or_default();
if tags.is_empty() {
output::print_message(&format!("No tags on {object} #{id}"));
} else {
for t in &tags {
println!(" {t}");
}
output::print_message(&format!("{} tags", tags.len()));
}
Ok(())
}
Loading
Loading