81 lines
2.1 KiB
Rust
81 lines
2.1 KiB
Rust
use std::error::Error;
|
|
|
|
use elefren::{
|
|
helpers::{cli, toml},
|
|
scopes::Scopes,
|
|
status_builder::Visibility,
|
|
Language, Mastodon, MastodonClient, Registration, StatusBuilder,
|
|
};
|
|
|
|
const FEDIVERSE_TOML_PATH: &str = "fediverse.toml";
|
|
|
|
pub trait Publisher {
|
|
fn publish(&self, content: String) -> Option<Box<dyn Error>>;
|
|
}
|
|
|
|
pub struct FediversePublisher {
|
|
client: Mastodon,
|
|
}
|
|
|
|
pub struct ConsolePublisher;
|
|
|
|
impl Publisher for ConsolePublisher {
|
|
fn publish(&self, content: String) -> Option<Box<dyn Error>> {
|
|
println!("Publishing content to stdout: {}", content);
|
|
None
|
|
}
|
|
}
|
|
|
|
impl ConsolePublisher {
|
|
pub fn new() -> ConsolePublisher {
|
|
ConsolePublisher {}
|
|
}
|
|
}
|
|
|
|
impl FediversePublisher {
|
|
pub fn new(fedi_url: String) -> Result<FediversePublisher, Box<dyn Error>> {
|
|
let fedi = if let Ok(data) = toml::from_file(FEDIVERSE_TOML_PATH.to_string()) {
|
|
Mastodon::from(data)
|
|
} else {
|
|
register(fedi_url)?
|
|
};
|
|
Ok(Self { client: fedi })
|
|
}
|
|
}
|
|
|
|
impl Publisher for FediversePublisher {
|
|
fn publish(&self, content: String) -> Option<Box<dyn Error>> {
|
|
let status_build_result = StatusBuilder::new()
|
|
.status(&content)
|
|
// .visibility(Visibility::Direct)
|
|
.visibility(Visibility::Public)
|
|
.sensitive(false)
|
|
.language(Language::Eng)
|
|
.build();
|
|
|
|
let status = match status_build_result {
|
|
Ok(status) => status,
|
|
Err(err) => return Some(Box::new(err)),
|
|
};
|
|
println!("Posting status [{}] to fediverse", &content);
|
|
|
|
match self.client.new_status(status) {
|
|
Ok(_) => None,
|
|
Err(err) => Some(Box::new(err)),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn register(fedi_url: String) -> Result<Mastodon, Box<dyn Error>> {
|
|
let registration = Registration::new(fedi_url)
|
|
.client_name("izzilis")
|
|
.scopes(Scopes::write_all())
|
|
.build()?;
|
|
let fediverse = cli::authenticate(registration)?;
|
|
|
|
// Save app data for using on the next run.
|
|
toml::to_file(&*fediverse, FEDIVERSE_TOML_PATH.to_string())?;
|
|
|
|
Ok(fediverse)
|
|
}
|