use serde::{Deserialize, Serialize};
use serde_json::json;
use url::Url;
use crate::{auth::TokenProvider, client::Client, Error};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostResponse {
pub id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextPost {
pub author_urn: String,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub link: Option<url::Url>,
#[serde(skip_serializing_if = "Option::is_none")]
pub visibility: Option<String>,
}
impl TextPost {
pub fn new(author_urn: impl Into<String>, text: impl Into<String>) -> Self {
Self {
author_urn: author_urn.into(),
text: text.into(),
link: None,
visibility: None,
}
}
pub fn with_link(mut self, link: Url) -> Self {
self.link = Some(link);
self
}
pub fn with_visibility(mut self, vis: impl Into<String>) -> Self {
self.visibility = Some(vis.into());
self
}
}
pub const DEFAULT_API_VERSION: &str = "202604";
pub struct PostsClient<TP: TokenProvider> {
inner: Client<TP>,
api_version: String,
}
impl<TP: TokenProvider> PostsClient<TP> {
#[must_use]
pub fn new(inner: Client<TP>) -> Self {
Self {
inner,
api_version: DEFAULT_API_VERSION.to_string(),
}
}
#[must_use]
pub fn with_api_version(mut self, version: impl Into<String>) -> Self {
self.api_version = version.into();
self
}
pub async fn create_text_post(&self, post: &TextPost) -> Result<PostResponse, Error> {
let url = self
.inner
.base()
.join("rest/posts")
.map_err(|e| Error::Config(format!("invalid base url: {e}")))?;
let mut commentary = post.text.trim().to_string();
if let Some(link) = &post.link {
if !commentary.is_empty() {
commentary.push_str("\n\n");
}
commentary.push_str(link.as_str());
}
let body = json!({
"author": post.author_urn,
"commentary": commentary,
"visibility": post.visibility.clone().unwrap_or_else(|| "PUBLIC".to_string()),
"distribution": { "feedDistribution": "MAIN_FEED" },
"lifecycleState": "PUBLISHED",
"isReshareDisabledByAuthor": false
});
let mut headers = self.inner.auth_headers()?;
headers.insert("X-Restli-Protocol-Version", "2.0.0".parse().unwrap());
headers.insert("LinkedIn-Version", self.api_version.parse().unwrap());
headers.insert("Content-Type", "application/json".parse().unwrap());
let resp = self
.inner
.http()
.post(url)
.headers(headers)
.json(&body)
.send()
.await?;
if resp.status().is_success() || resp.status().as_u16() == 201 {
let id = resp
.headers()
.get("x-restli-id")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
.or_else(|| {
resp.headers()
.get("location")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
})
.unwrap_or_else(|| "created".to_string());
return Ok(PostResponse { id });
}
if resp.status().as_u16() == 429 {
let retry_after = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0);
return Err(Error::RateLimited { retry_after });
}
let status = resp.status().as_u16();
let message = resp.text().await.unwrap_or_default();
Err(Error::Api { status, message })
}
}