1use crate::commands::Command;
2use anyhow::{Context, Result};
3use api::agent::bluesky::{AtprotoServiceType, BSKY_CHAT_DID};
4use api::types::LimitedNonZeroU8;
5use api::types::string::{AtIdentifier, Datetime, Handle, RecordKey};
6use bsky_sdk::BskyAgent;
7use bsky_sdk::agent::config::{Config, FileStore};
8use bsky_sdk::api;
9use serde::Serialize;
10use std::ffi::OsStr;
11use std::path::PathBuf;
12use tokio::fs::{File, create_dir_all};
13use tokio::io::AsyncReadExt;
14
15pub struct Runner {
16 agent: BskyAgent,
17 limit: LimitedNonZeroU8<100>,
18 debug: bool,
19 config_path: PathBuf,
20}
21
22impl Runner {
23 pub async fn new(
24 pds_host: String,
25 limit: LimitedNonZeroU8<100>,
26 debug: bool,
27 is_login: bool,
28 ) -> Result<Self> {
29 let config_dir = dirs::config_dir()
30 .with_context(|| format!("No config dir: {:?}", dirs::config_dir()))?;
31 let dir = config_dir.join("bsky-cli");
32 create_dir_all(&dir).await?;
33 let config_path = dir.join("config.json");
34
35 let agent = if is_login {
36 BskyAgent::builder()
37 .config(Config { endpoint: pds_host, ..Default::default() })
38 .build()
39 .await?
40 } else {
41 let store = FileStore::new(&config_path);
42 let agent = BskyAgent::builder()
43 .config(Config::load(&store).await.with_context(|| "Not logged in")?)
44 .build()
45 .await?;
46 agent.to_config().await.save(&store).await?;
47 agent
48 };
49 Ok(Self { agent, limit, debug, config_path })
50 }
51 pub async fn run(&self, command: Command) -> Result<()> {
52 let limit = self.limit;
53 match command {
54 Command::Login(args) => {
55 self.agent.login(args.identifier, args.password).await?;
56 let preferences = self.agent.get_preferences(true).await?;
58 self.agent.configure_labelers_from_preferences(&preferences);
59 self.agent.to_config().await.save(&FileStore::new(&self.config_path)).await?;
61 println!("Login successful! Saved config to {:?}", self.config_path);
62 Ok(())
63 }
64 Command::GetTimeline => self.print(
65 &self
66 .agent
67 .api
68 .app
69 .bsky
70 .feed
71 .get_timeline(
72 api::app::bsky::feed::get_timeline::ParametersData {
73 algorithm: None,
74 cursor: None,
75 limit: Some(limit),
76 }
77 .into(),
78 )
79 .await?,
80 ),
81 Command::GetAuthorFeed(args) => self.print(
82 &self
83 .agent
84 .api
85 .app
86 .bsky
87 .feed
88 .get_author_feed(
89 api::app::bsky::feed::get_author_feed::ParametersData {
90 actor: args.actor.unwrap_or(self.handle().await?.into()),
91 cursor: None,
92 filter: None,
93 include_pins: None,
94 limit: Some(limit),
95 }
96 .into(),
97 )
98 .await?,
99 ),
100 Command::GetLikes(args) => self.print(
101 &self
102 .agent
103 .api
104 .app
105 .bsky
106 .feed
107 .get_likes(
108 api::app::bsky::feed::get_likes::ParametersData {
109 cid: None,
110 cursor: None,
111 limit: Some(limit),
112 uri: args.uri.to_string(),
113 }
114 .into(),
115 )
116 .await?,
117 ),
118 Command::GetRepostedBy(args) => self.print(
119 &self
120 .agent
121 .api
122 .app
123 .bsky
124 .feed
125 .get_reposted_by(
126 api::app::bsky::feed::get_reposted_by::ParametersData {
127 cid: None,
128 cursor: None,
129 limit: Some(limit),
130 uri: args.uri.to_string(),
131 }
132 .into(),
133 )
134 .await?,
135 ),
136 Command::GetActorFeeds(args) => self.print(
137 &self
138 .agent
139 .api
140 .app
141 .bsky
142 .feed
143 .get_actor_feeds(
144 api::app::bsky::feed::get_actor_feeds::ParametersData {
145 actor: args.actor.unwrap_or(self.handle().await?.into()),
146 cursor: None,
147 limit: Some(limit),
148 }
149 .into(),
150 )
151 .await?,
152 ),
153 Command::GetFeed(args) => self.print(
154 &self
155 .agent
156 .api
157 .app
158 .bsky
159 .feed
160 .get_feed(
161 api::app::bsky::feed::get_feed::ParametersData {
162 cursor: None,
163 feed: args.uri.to_string(),
164 limit: Some(limit),
165 }
166 .into(),
167 )
168 .await?,
169 ),
170 Command::GetListFeed(args) => self.print(
171 &self
172 .agent
173 .api
174 .app
175 .bsky
176 .feed
177 .get_list_feed(
178 api::app::bsky::feed::get_list_feed::ParametersData {
179 cursor: None,
180 limit: Some(limit),
181 list: args.uri.to_string(),
182 }
183 .into(),
184 )
185 .await?,
186 ),
187 Command::GetFollows(args) => self.print(
188 &self
189 .agent
190 .api
191 .app
192 .bsky
193 .graph
194 .get_follows(
195 api::app::bsky::graph::get_follows::ParametersData {
196 actor: args.actor.unwrap_or(self.handle().await?.into()),
197 cursor: None,
198 limit: Some(limit),
199 sort: None,
200 }
201 .into(),
202 )
203 .await?,
204 ),
205 Command::GetFollowers(args) => self.print(
206 &self
207 .agent
208 .api
209 .app
210 .bsky
211 .graph
212 .get_followers(
213 api::app::bsky::graph::get_followers::ParametersData {
214 actor: args.actor.unwrap_or(self.handle().await?.into()),
215 cursor: None,
216 limit: Some(limit),
217 sort: None,
218 }
219 .into(),
220 )
221 .await?,
222 ),
223 Command::GetLists(args) => self.print(
224 &self
225 .agent
226 .api
227 .app
228 .bsky
229 .graph
230 .get_lists(
231 api::app::bsky::graph::get_lists::ParametersData {
232 actor: args.actor.unwrap_or(self.handle().await?.into()),
233 cursor: None,
234 limit: Some(limit),
235 purposes: None,
236 }
237 .into(),
238 )
239 .await?,
240 ),
241 Command::GetList(args) => self.print(
242 &self
243 .agent
244 .api
245 .app
246 .bsky
247 .graph
248 .get_list(
249 api::app::bsky::graph::get_list::ParametersData {
250 cursor: None,
251 limit: Some(limit),
252 list: args.uri.to_string(),
253 }
254 .into(),
255 )
256 .await?,
257 ),
258 Command::GetProfile(args) => self.print(
259 &self
260 .agent
261 .api
262 .app
263 .bsky
264 .actor
265 .get_profile(
266 api::app::bsky::actor::get_profile::ParametersData {
267 actor: args.actor.unwrap_or(self.handle().await?.into()),
268 }
269 .into(),
270 )
271 .await?,
272 ),
273 Command::GetPreferences => self.print(
274 &self
275 .agent
276 .api
277 .app
278 .bsky
279 .actor
280 .get_preferences(
281 api::app::bsky::actor::get_preferences::ParametersData {}.into(),
282 )
283 .await?,
284 ),
285 Command::ListNotifications => self.print(
286 &self
287 .agent
288 .api
289 .app
290 .bsky
291 .notification
292 .list_notifications(
293 api::app::bsky::notification::list_notifications::ParametersData {
294 cursor: None,
295 limit: Some(limit),
296 priority: None,
297 seen_at: None,
298 reasons: None,
299 }
300 .into(),
301 )
302 .await?,
303 ),
304 Command::ListConvos => self.print(
305 &self
306 .agent
307 .api_with_proxy(
308 BSKY_CHAT_DID.parse().expect("valid DID"),
309 AtprotoServiceType::BskyChat,
310 )
311 .chat
312 .bsky
313 .convo
314 .list_convos(
315 api::chat::bsky::convo::list_convos::ParametersData {
316 cursor: None,
317 kind: None,
318 limit: Some(limit),
319 lock_status: None,
320 read_state: None,
321 status: None,
322 }
323 .into(),
324 )
325 .await?,
326 ),
327 Command::SendConvoMessage(args) => {
328 let did = match args.actor {
329 AtIdentifier::Handle(handle) => {
330 self.agent
331 .api
332 .com
333 .atproto
334 .identity
335 .resolve_handle(
336 api::com::atproto::identity::resolve_handle::ParametersData {
337 handle: handle.clone(),
338 }
339 .into(),
340 )
341 .await?
342 .data
343 .did
344 }
345 AtIdentifier::Did(did) => did,
346 };
347 let chat = &self
348 .agent
349 .api_with_proxy(
350 BSKY_CHAT_DID.parse().expect("valid DID"),
351 AtprotoServiceType::BskyChat,
352 )
353 .chat;
354 let convo = chat
355 .bsky
356 .convo
357 .get_convo_for_members(
358 api::chat::bsky::convo::get_convo_for_members::ParametersData {
359 members: vec![did],
360 }
361 .into(),
362 )
363 .await?;
364 self.print(
365 &chat
366 .bsky
367 .convo
368 .send_message(
369 api::chat::bsky::convo::send_message::InputData {
370 convo_id: convo.data.convo.data.id,
371 message: api::chat::bsky::convo::defs::MessageInputData {
372 embed: None,
373 facets: None,
374 reply_to: None,
375 text: args.text,
376 }
377 .into(),
378 }
379 .into(),
380 )
381 .await?,
382 )
383 }
384 Command::CreatePost(args) => {
385 let mut images = Vec::new();
386 for image in &args.images {
387 if let Ok(mut file) = File::open(image).await {
388 let mut buf = Vec::new();
389 file.read_to_end(&mut buf).await.expect("read image file");
390 let output = self
391 .agent
392 .api
393 .com
394 .atproto
395 .repo
396 .upload_blob(buf)
397 .await
398 .expect("upload blob");
399 images.push(
400 api::app::bsky::embed::images::ImageData {
401 alt: image
402 .file_name()
403 .map(OsStr::to_string_lossy)
404 .unwrap_or_default()
405 .into(),
406 aspect_ratio: None,
407 image: output.data.blob,
408 }
409 .into(),
410 )
411 }
412 }
413 let embed = Some(api::types::Union::Refs(
414 api::app::bsky::feed::post::RecordEmbedRefs::AppBskyEmbedImagesMain(Box::new(
415 api::app::bsky::embed::images::MainData { images }.into(),
416 )),
417 ));
418 self.print(
419 &self
420 .agent
421 .create_record(api::app::bsky::feed::post::RecordData {
422 created_at: Datetime::now(),
423 embed,
424 entities: None,
425 facets: None,
426 labels: None,
427 langs: None,
428 reply: None,
429 tags: None,
430 text: args.text,
431 })
432 .await?,
433 )
434 }
435 Command::DeletePost(args) => self.print(
436 &self
437 .agent
438 .api
439 .com
440 .atproto
441 .repo
442 .delete_record(
443 api::com::atproto::repo::delete_record::InputData {
444 collection: "app.bsky.feed.post".parse().expect("valid"),
445 repo: self.handle().await?.into(),
446 rkey: RecordKey::new(args.uri.rkey).map_err(|e| anyhow::anyhow!(e))?,
447 swap_commit: None,
448 swap_record: None,
449 }
450 .into(),
451 )
452 .await?,
453 ),
454 }
455 }
456 fn print<T: std::fmt::Debug + Serialize>(&self, result: &T) -> Result<()> {
457 if self.debug {
458 println!("{:#?}", result);
459 } else {
460 println!("{}", serde_json::to_string_pretty(result)?);
461 }
462 Ok(())
463 }
464 async fn handle(&self) -> Result<Handle> {
465 Ok(self.agent.get_session().await.with_context(|| "Not logged in")?.data.handle)
466 }
467}