1use anyhow::{anyhow, Result};
5use hashiverse_lib::client::hashiverse_client::HashiverseClient;
6use hashiverse_lib::protocol::posting::encoded_post::EncodedPostV1;
7use hashiverse_lib::tools::buckets::{BucketLocation, BucketType};
8use hashiverse_lib::tools::plain_text_post::convert_text_to_hashiverse_html;
9use hashiverse_lib::tools::types::Id;
10use serde::Serialize;
11
12use crate::cli_args::{Command, ENV_KEYPHRASE, ENV_PASSWORD, ENV_PROFILE};
13use crate::unlock::is_guest;
14use crate::render::{format_json, format_post_submitted_text, format_posts_text, format_trending_text};
15
16#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
17pub struct CliPost {
18 pub post_id: String,
19 pub time_millis: i64,
20 pub client_id: String,
21 pub bucket_location: String,
22 pub post_html: String,
23 pub healed: bool,
24}
25
26#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
27pub struct CliPostSubmitted {
28 pub post_id: String,
29 pub bucket_locations: Vec<String>,
30}
31
32#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
33pub struct CliTrendingHashtag {
34 pub hashtag: String,
35 pub count: u64,
36}
37
38pub fn cli_post_from_timeline_entry(bucket_location: &BucketLocation, encoded_post: EncodedPostV1, healed: bool) -> Result<CliPost> {
39 let client_id = encoded_post.header.client_id()?;
40 Ok(CliPost {
41 post_id: encoded_post.post_id.to_hex_str(),
42 time_millis: encoded_post.header.time_millis.0,
43 client_id: client_id.id_hex(),
44 bucket_location: bucket_location.to_html_attr(),
45 post_html: encoded_post.post,
46 healed,
47 })
48}
49
50pub fn normalise_hashtag(hashtag: &str) -> String {
52 let trimmed = hashtag.trim();
53 trimmed.strip_prefix('#').unwrap_or(trimmed).to_string()
54}
55
56pub async fn post(hashiverse_client: &HashiverseClient, text: &str) -> Result<CliPostSubmitted> {
57 if is_guest(hashiverse_client) {
58 return Err(anyhow!("posting requires an identity: set {} or {}, together with {} (or `login <client_id>` in the REPL)", ENV_KEYPHRASE, ENV_PROFILE, ENV_PASSWORD));
59 }
60
61 let post_html = convert_text_to_hashiverse_html(text);
62 let (submit_post_commit_tokens, (encoded_post, _encoded_post_bytes)) = hashiverse_client.submit_post(&post_html).await?;
63
64 let mut bucket_locations: Vec<String> = Vec::new();
65 for submit_post_commit_token in &submit_post_commit_tokens {
66 let bucket_location = submit_post_commit_token.bucket_location.to_html_attr();
67 if !bucket_locations.contains(&bucket_location) {
68 bucket_locations.push(bucket_location);
69 }
70 }
71
72 Ok(CliPostSubmitted {
73 post_id: encoded_post.post_id.to_hex_str(),
74 bucket_locations,
75 })
76}
77
78async fn timeline(hashiverse_client: &HashiverseClient, bucket_type: BucketType, base_id: &Id, pages: u32) -> Result<Vec<CliPost>> {
79 let mut cli_posts = Vec::new();
80 for _ in 0..pages.max(1) {
81 let (timeline_entries, _oldest_processed_time_millis) = hashiverse_client.single_timeline_get_more(bucket_type, base_id).await?;
82 for (bucket_location, encoded_post, _encoded_post_bytes, healed) in timeline_entries {
83 match cli_post_from_timeline_entry(&bucket_location, encoded_post, healed) {
84 Ok(cli_post) => cli_posts.push(cli_post),
85 Err(error) => log::warn!("Skipping post with bad header: {}", error),
86 }
87 }
88 }
89 Ok(cli_posts)
90}
91
92pub async fn user_timeline(hashiverse_client: &HashiverseClient, client_id_hex: &str, pages: u32) -> Result<Vec<CliPost>> {
93 let base_id = Id::from_hex_str(client_id_hex.trim())?;
94 timeline(hashiverse_client, BucketType::User, &base_id, pages).await
95}
96
97pub async fn hashtag_timeline(hashiverse_client: &HashiverseClient, hashtag: &str, pages: u32) -> Result<Vec<CliPost>> {
98 let base_id = Id::from_hashtag_str(&normalise_hashtag(hashtag))?;
99 timeline(hashiverse_client, BucketType::Hashtag, &base_id, pages).await
100}
101
102pub async fn trending(hashiverse_client: &HashiverseClient, limit: u16) -> Result<Vec<CliTrendingHashtag>> {
103 let trending_hashtags_fetch_response = hashiverse_client.fetch_trending_hashtags(limit).await?;
104 Ok(trending_hashtags_fetch_response
105 .trending_hashtags
106 .into_iter()
107 .map(|trending_hashtag| CliTrendingHashtag { hashtag: trending_hashtag.hashtag, count: trending_hashtag.count })
108 .collect())
109}
110
111pub async fn run_command(hashiverse_client: &HashiverseClient, command: &Command, json: bool) -> Result<String> {
114 match command {
115 Command::Post { text } => {
116 let cli_post_submitted = post(hashiverse_client, &text.join(" ")).await?;
117 if json { format_json(&cli_post_submitted) } else { Ok(format_post_submitted_text(&cli_post_submitted)) }
118 }
119 Command::User { client_id_hex, pages } => {
120 let cli_posts = user_timeline(hashiverse_client, client_id_hex, *pages).await?;
121 if json { format_json(&cli_posts) } else { Ok(format_posts_text(&cli_posts)) }
122 }
123 Command::Hashtag { hashtag, pages } => {
124 let cli_posts = hashtag_timeline(hashiverse_client, hashtag, *pages).await?;
125 if json { format_json(&cli_posts) } else { Ok(format_posts_text(&cli_posts)) }
126 }
127 Command::Trending { limit } => {
128 let cli_trending_hashtags = trending(hashiverse_client, *limit).await?;
129 if json { format_json(&cli_trending_hashtags) } else { Ok(format_trending_text(&cli_trending_hashtags)) }
130 }
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137
138 #[test]
139 fn normalise_hashtag_strips_one_hash_and_whitespace() {
140 assert_eq!(normalise_hashtag("#Rust"), "Rust");
141 assert_eq!(normalise_hashtag(" rust "), "rust");
142 assert_eq!(normalise_hashtag("##rust"), "#rust");
143 }
144
145 #[test]
146 fn hashtag_with_and_without_hash_map_to_same_bucket_id() {
147 let with_hash = Id::from_hashtag_str(&normalise_hashtag("#Rust")).unwrap();
148 let without_hash = Id::from_hashtag_str(&normalise_hashtag("rust")).unwrap();
149 assert_eq!(with_hash, without_hash);
150 }
151}