A better Rust ATProto crate
at main 2.7 kB view raw
1use clap::Parser; 2use jacquard::CowStr; 3use jacquard::api::app_bsky::embed::images::{Image, Images}; 4use jacquard::api::app_bsky::feed::post::{Post, PostEmbed}; 5use jacquard::client::{Agent, AgentSessionExt, FileAuthStore}; 6use jacquard::oauth::client::OAuthClient; 7use jacquard::oauth::loopback::LoopbackConfig; 8use jacquard::types::blob::MimeType; 9use jacquard::types::string::Datetime; 10use miette::IntoDiagnostic; 11use std::path::PathBuf; 12 13#[derive(Parser, Debug)] 14#[command(author, version, about = "Create a post with an image")] 15struct Args { 16 /// Handle (e.g., alice.bsky.social), DID, or PDS URL 17 input: CowStr<'static>, 18 19 /// Post text 20 #[arg(short, long)] 21 text: String, 22 23 /// Path to image file 24 #[arg(short, long)] 25 image: PathBuf, 26 27 /// Alt text for image 28 #[arg(long)] 29 alt: Option<String>, 30 31 /// Path to auth store file (will be created if missing) 32 #[arg(long, default_value = "/tmp/jacquard-oauth-session.json")] 33 store: String, 34} 35 36#[tokio::main] 37async fn main() -> miette::Result<()> { 38 let args = Args::parse(); 39 40 let oauth = OAuthClient::with_default_config(FileAuthStore::new(&args.store)); 41 let session = oauth 42 .login_with_local_server(args.input, Default::default(), LoopbackConfig::default()) 43 .await?; 44 45 let agent: Agent<_> = Agent::from(session); 46 47 // Read image file 48 let image_data = std::fs::read(&args.image).into_diagnostic()?; 49 50 // Infer mime type from extension 51 let mime_str = match args.image.extension().and_then(|s| s.to_str()) { 52 Some("jpg") | Some("jpeg") => "image/jpeg", 53 Some("png") => "image/png", 54 Some("gif") => "image/gif", 55 Some("webp") => "image/webp", 56 _ => "image/jpeg", // default 57 }; 58 let mime_type = MimeType::new_static(mime_str); 59 60 println!("Uploading image..."); 61 let blob = agent.upload_blob(image_data, mime_type).await?; 62 63 // Create post with image embed 64 let post = Post { 65 text: CowStr::from(args.text), 66 created_at: Datetime::now(), 67 embed: Some(PostEmbed::Images(Box::new(Images { 68 images: vec![Image { 69 alt: CowStr::from(args.alt.unwrap_or_default()), 70 image: blob, 71 aspect_ratio: None, 72 extra_data: Default::default(), 73 }], 74 extra_data: Default::default(), 75 }))), 76 entities: None, 77 facets: None, 78 labels: None, 79 langs: None, 80 reply: None, 81 tags: None, 82 extra_data: Default::default(), 83 }; 84 85 let output = agent.create_record(post, None).await?; 86 println!("Created post with image: {}", output.uri); 87 88 Ok(()) 89}