Skip to main content

gen_linkedin/
post.rs

1use std::{
2    fs::{self, File},
3    io::BufReader,
4    path::{Path, PathBuf},
5};
6
7use thiserror::Error;
8
9use crate::{
10    draft::LinkedinFile,
11    frontmatter_writeback::{write_linkedin_date_field, FmWriteError},
12};
13
14/// Errors that can occur during LinkedIn post publishing.
15#[derive(Debug, Error)]
16pub enum PostError {
17    /// I/O error reading, writing, or deleting files.
18    #[error("io error: {0}")]
19    Io(#[from] std::io::Error),
20    /// JSON deserialization error loading a `.linkedin` file.
21    #[error("json error: {0}")]
22    Json(#[from] serde_json::Error),
23    /// Frontmatter write-back error.
24    #[error("frontmatter write error: {0}")]
25    FmWrite(#[from] FmWriteError),
26    /// LinkedIn API error.
27    #[error("linkedin api error: {0}")]
28    Api(String),
29    /// Missing required configuration value.
30    #[error("missing configuration: {0}")]
31    Config(String),
32}
33
34#[derive(Debug, Clone, PartialEq)]
35enum LinkedinPostState {
36    Read,
37    Posted,
38    Deleted,
39}
40
41/// A loaded `.linkedin` draft file ready for publishing.
42#[derive(Debug)]
43pub struct LinkedinPost {
44    file_path: PathBuf,
45    record: LinkedinFile,
46    state: LinkedinPostState,
47}
48
49impl LinkedinPost {
50    fn new(record: LinkedinFile, file_path: PathBuf) -> Self {
51        Self {
52            file_path,
53            record,
54            state: LinkedinPostState::Read,
55        }
56    }
57
58    /// Path to the source `.md` file, if recorded in the `.linkedin` file.
59    pub fn source_path(&self) -> Option<&PathBuf> {
60        self.record.source_path.as_ref()
61    }
62
63    /// The LinkedIn post text.
64    pub fn text(&self) -> &str {
65        &self.record.text
66    }
67
68    /// The optional link to attach.
69    pub fn link(&self) -> Option<&str> {
70        self.record.link.as_deref()
71    }
72
73    fn set_posted(&mut self) {
74        self.state = LinkedinPostState::Posted;
75    }
76
77    fn set_deleted(&mut self) {
78        self.state = LinkedinPostState::Deleted;
79    }
80}
81
82/// Manages publishing staged `.linkedin` draft files to LinkedIn.
83pub struct Post {
84    access_token: String,
85    author_urn: String,
86    api_version: String,
87    pub(crate) linkedin_posts: Vec<LinkedinPost>,
88    deleted: usize,
89    testing: bool,
90}
91
92impl Post {
93    /// Create a new `Post` manager with the given credentials.
94    pub fn new(access_token: &str, author_urn: &str) -> Self {
95        let testing = std::env::var("TESTING").is_ok();
96        Self {
97            access_token: access_token.to_string(),
98            author_urn: author_urn.to_string(),
99            api_version: crate::posts::DEFAULT_API_VERSION.to_string(),
100            linkedin_posts: Vec::new(),
101            deleted: 0,
102            testing,
103        }
104    }
105
106    /// Override the LinkedIn API version sent in the `LinkedIn-Version` header.
107    #[must_use]
108    pub fn with_api_version(mut self, version: impl Into<String>) -> Self {
109        self.api_version = version.into();
110        self
111    }
112
113    /// Force testing mode (no actual API calls). Used in unit tests.
114    #[cfg(test)]
115    pub fn with_testing(mut self) -> Self {
116        self.testing = true;
117        self
118    }
119
120    /// Load all `.linkedin` files from `store_dir`.
121    pub fn load<P>(&mut self, store_dir: P) -> Result<&mut Self, PostError>
122    where
123        P: AsRef<Path>,
124    {
125        let dir = store_dir.as_ref();
126        if !dir.is_dir() {
127            return Ok(self);
128        }
129        for entry in fs::read_dir(dir)? {
130            let entry = entry?;
131            let path = entry.path();
132            if path.extension().and_then(|e| e.to_str()) == Some("linkedin") {
133                let file = File::open(&path)?;
134                let reader = BufReader::new(file);
135                let record: LinkedinFile = serde_json::from_reader(reader)?;
136                self.linkedin_posts.push(LinkedinPost::new(record, path));
137            }
138        }
139        Ok(self)
140    }
141
142    /// Publish all loaded posts to LinkedIn.
143    ///
144    /// In test mode (`TESTING=true` env var) posts are not actually sent.
145    pub async fn post_to_linkedin(&mut self) -> Result<&mut Self, PostError> {
146        if self.testing {
147            log::info!("TESTING mode — no posts will be sent to LinkedIn.");
148        }
149
150        // Only build the HTTP client when actually needed.
151        let posts_client = if !self.testing {
152            use crate::{auth::StaticTokenProvider, client::Client, posts::PostsClient};
153            let token = StaticTokenProvider(self.access_token.clone());
154            let client = Client::new(token).map_err(|e| PostError::Api(e.to_string()))?;
155            Some(PostsClient::new(client).with_api_version(&self.api_version))
156        } else {
157            None
158        };
159
160        for li_post in self
161            .linkedin_posts
162            .iter_mut()
163            .filter(|p| p.state == LinkedinPostState::Read)
164        {
165            publish_one(
166                self.testing,
167                &self.author_urn,
168                li_post,
169                posts_client.as_ref(),
170            )
171            .await?;
172        }
173
174        Ok(self)
175    }
176
177    /// Delete `.linkedin` files for all successfully posted content and write
178    /// `[linkedin].published = <today>` into the source markdown file.
179    pub fn delete_posted_posts(&mut self) -> Result<&mut Self, PostError> {
180        let today = {
181            let today = chrono::Utc::now().date_naive();
182            today
183                .format("%Y-%m-%d")
184                .to_string()
185                .parse()
186                .expect("valid date")
187        };
188
189        for li_post in self
190            .linkedin_posts
191            .iter_mut()
192            .filter(|p| p.state == LinkedinPostState::Posted)
193        {
194            // Write published date into source frontmatter.
195            if let Some(src) = li_post.source_path() {
196                if let Err(e) = write_linkedin_date_field(src, "published", today) {
197                    log::warn!("Failed to write [linkedin].published to {src:?}: {e}");
198                }
199            }
200
201            // Delete the .linkedin file.
202            if let Err(e) = fs::remove_file(&li_post.file_path) {
203                log::warn!("Failed to delete {:?}: {e}", li_post.file_path);
204            } else {
205                li_post.set_deleted();
206                self.deleted += 1;
207            }
208        }
209
210        Ok(self)
211    }
212
213    /// Number of posts successfully deleted (published + cleaned up).
214    pub fn count_deleted(&self) -> usize {
215        self.deleted
216    }
217}
218
219async fn publish_one(
220    testing: bool,
221    author_urn: &str,
222    li_post: &mut LinkedinPost,
223    posts_client: Option<&crate::posts::PostsClient<crate::auth::StaticTokenProvider>>,
224) -> Result<(), PostError> {
225    // Skip if source markdown already has [linkedin].published.
226    if let Some(src) = li_post.source_path() {
227        if crate::frontmatter_writeback::read_linkedin_date_field(src, "published").is_some() {
228            log::debug!("Skipping — [linkedin].published already set in {src:?}");
229            return Ok(());
230        }
231    }
232
233    if testing {
234        log::info!("(test) would post: {}", li_post.text());
235        li_post.set_posted();
236    } else {
237        use crate::posts::TextPost;
238        let client = posts_client.expect("client built above");
239        let mut text_post = TextPost::new(author_urn, li_post.text());
240        if let Some(link) = li_post.link() {
241            text_post = text_post.with_link(
242                link.parse()
243                    .map_err(|e: url::ParseError| PostError::Api(e.to_string()))?,
244            );
245        }
246        match client.create_text_post(&text_post).await {
247            Ok(_) => {
248                log::info!("Posted to LinkedIn: {}", li_post.text());
249                li_post.set_posted();
250            }
251            Err(e) => {
252                log::warn!("Failed to post to LinkedIn: {e}");
253            }
254        }
255    }
256
257    Ok(())
258}
259
260#[cfg(test)]
261mod tests {
262    use tempfile::tempdir;
263
264    use super::*;
265
266    fn write_linkedin_file(dir: &Path, name: &str, text: &str, source: Option<&Path>) -> PathBuf {
267        let record = LinkedinFile {
268            text: text.to_string(),
269            link: None,
270            created_at: "2026-04-03".to_string(),
271            source_path: source.map(|p| p.to_path_buf()),
272        };
273        let path = dir.join(name);
274        let file = File::create(&path).unwrap();
275        serde_json::to_writer(&file, &record).unwrap();
276        path
277    }
278
279    fn write_md_with_created(dir: &Path, name: &str) -> PathBuf {
280        let content = "+++\ntitle = \"Test\"\n\n[linkedin]\ndescription = \"hello\"\ncreated = 2026-04-03\n+++\n\nBody.\n";
281        let path = dir.join(name);
282        fs::write(&path, content).unwrap();
283        path
284    }
285
286    // RED: Post::load reads .linkedin files
287
288    #[test]
289    fn test_load_reads_linkedin_files() {
290        let dir = tempdir().unwrap();
291        write_linkedin_file(dir.path(), "post.linkedin", "Hello", None);
292
293        let mut post = Post::new("token", "urn:li:organization:123");
294        post.load(dir.path()).unwrap();
295
296        assert_eq!(post.linkedin_posts.len(), 1);
297        assert_eq!(post.linkedin_posts[0].text(), "Hello");
298    }
299
300    // RED: Post::load ignores non-.linkedin files
301
302    #[test]
303    fn test_load_ignores_other_files() {
304        let dir = tempdir().unwrap();
305        write_linkedin_file(dir.path(), "post.linkedin", "Hello", None);
306        fs::write(dir.path().join("readme.txt"), "ignore me").unwrap();
307
308        let mut post = Post::new("token", "urn:li:organization:123");
309        post.load(dir.path()).unwrap();
310
311        assert_eq!(post.linkedin_posts.len(), 1);
312    }
313
314    // RED: Post::load reads source_path from file
315
316    #[test]
317    fn test_load_reads_source_path() {
318        let dir = tempdir().unwrap();
319        let md_path = dir.path().join("my-post.md");
320        write_linkedin_file(dir.path(), "post.linkedin", "Hello", Some(&md_path));
321
322        let mut post = Post::new("token", "urn:li:organization:123");
323        post.load(dir.path()).unwrap();
324
325        assert_eq!(post.linkedin_posts[0].source_path(), Some(&md_path));
326    }
327
328    // RED: delete_posted_posts writes published into source markdown
329
330    #[test]
331    fn test_delete_posted_posts_writes_published() {
332        let dir = tempdir().unwrap();
333        let md_path = write_md_with_created(dir.path(), "my-post.md");
334        write_linkedin_file(dir.path(), "post.linkedin", "Hello", Some(&md_path));
335
336        let mut post = Post::new("token", "urn:li:organization:123");
337        post.load(dir.path()).unwrap();
338        assert_eq!(post.linkedin_posts.len(), 1);
339
340        // Manually set state to Posted (simulates a successful API call).
341        post.linkedin_posts[0].set_posted();
342        post.delete_posted_posts().unwrap();
343
344        let content = fs::read_to_string(&md_path).unwrap();
345        assert!(
346            content.contains("published ="),
347            "frontmatter should contain published: {content}"
348        );
349    }
350
351    // RED: delete_posted_posts removes the .linkedin file
352
353    #[test]
354    fn test_delete_posted_posts_removes_file() {
355        let dir = tempdir().unwrap();
356        let md_path = write_md_with_created(dir.path(), "my-post.md");
357        let li_path = write_linkedin_file(dir.path(), "post.linkedin", "Hello", Some(&md_path));
358
359        let mut post = Post::new("token", "urn:li:organization:123");
360        post.load(dir.path()).unwrap();
361        post.linkedin_posts[0].set_posted();
362        post.delete_posted_posts().unwrap();
363
364        assert!(!li_path.exists(), ".linkedin file should be deleted");
365        assert_eq!(post.count_deleted(), 1);
366    }
367
368    // RED: post_to_linkedin in TESTING mode marks posts as Posted
369
370    #[tokio::test]
371    async fn test_post_to_linkedin_testing_mode() {
372        let dir = tempdir().unwrap();
373        write_linkedin_file(dir.path(), "post.linkedin", "Hello LinkedIn", None);
374
375        let mut post = Post::new("token", "urn:li:organization:123").with_testing();
376        post.load(dir.path()).unwrap();
377        post.post_to_linkedin().await.unwrap();
378
379        assert_eq!(
380            post.linkedin_posts[0].state,
381            LinkedinPostState::Posted,
382            "post should be marked Posted in test mode"
383        );
384    }
385
386    // RED: post_to_linkedin skips posts with [linkedin].published already set
387
388    #[tokio::test]
389    async fn test_post_to_linkedin_skips_already_published() {
390        let dir = tempdir().unwrap();
391        let md_content = "+++\ntitle = \"T\"\n\n[linkedin]\ndescription = \"d\"\ncreated = 2026-04-01\npublished = 2026-04-01\n+++\n\nBody.\n";
392        let md_path = dir.path().join("post.md");
393        fs::write(&md_path, md_content).unwrap();
394        write_linkedin_file(dir.path(), "post.linkedin", "Hello", Some(&md_path));
395
396        let mut post = Post::new("token", "urn:li:organization:123").with_testing();
397        post.load(dir.path()).unwrap();
398        post.post_to_linkedin().await.unwrap();
399
400        assert_eq!(
401            post.linkedin_posts[0].state,
402            LinkedinPostState::Read,
403            "already-published post should remain in Read state"
404        );
405    }
406
407    // RED: LinkedinFile roundtrips through JSON without source_path
408
409    #[test]
410    fn test_linkedin_file_deserializes_without_source_path() {
411        let json = r#"{"text":"Hello","created_at":"2026-04-03"}"#;
412        let f: LinkedinFile = serde_json::from_str(json).unwrap();
413        assert!(f.source_path.is_none());
414        assert_eq!(f.text, "Hello");
415    }
416}