mastodon-async/examples/register/mod.rs

88 lines
2.3 KiB
Rust
Raw Normal View History

2022-11-27 14:44:43 +00:00
#![cfg_attr(not(feature = "toml"), allow(dead_code))]
#![cfg_attr(not(feature = "toml"), allow(unused_imports))]
2022-12-22 18:19:49 +00:00
pub use mastodon_async::prelude::*;
2022-11-27 14:44:43 +00:00
2022-12-22 17:29:13 +00:00
use std::io;
2022-11-27 14:44:43 +00:00
#[cfg(feature = "toml")]
2022-12-22 18:19:49 +00:00
use mastodon_async::helpers::toml;
use mastodon_async::{helpers::cli, Result};
2022-11-27 14:44:43 +00:00
#[allow(dead_code)]
#[cfg(all(feature = "toml", feature = "mt"))]
2022-12-22 17:29:13 +00:00
#[tokio::main]
async fn main() -> Result<()> {
register().await?;
2022-11-27 14:44:43 +00:00
Ok(())
}
#[allow(dead_code)]
#[cfg(all(feature = "toml", not(feature = "mt")))]
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
register().await?;
Ok(())
}
2022-11-27 14:44:43 +00:00
#[allow(dead_code)]
#[cfg(feature = "toml")]
2022-12-22 17:29:13 +00:00
pub async fn get_mastodon_data() -> Result<Mastodon> {
2022-11-27 14:44:43 +00:00
if let Ok(data) = toml::from_file("mastodon-data.toml") {
Ok(Mastodon::from(data))
} else {
2022-12-22 17:29:13 +00:00
register().await
2022-11-27 14:44:43 +00:00
}
}
#[cfg(feature = "toml")]
2022-12-22 17:29:13 +00:00
pub async fn register() -> Result<Mastodon> {
2022-11-27 14:44:43 +00:00
let website = read_line("Please enter your mastodon instance url:")?;
let registration = Registration::new(website.trim())
.client_name("elefren-examples")
.scopes(Scopes::all())
2022-12-22 17:29:13 +00:00
.website("https://github.com/dscottboggs/mastodon-async")
.build()
.await?;
let mastodon = cli::authenticate(registration).await?;
2022-11-27 14:44:43 +00:00
// Save app data for using on the next run.
2022-12-22 17:29:13 +00:00
toml::to_file(&mastodon.data, "mastodon-data.toml")?;
2022-11-27 14:44:43 +00:00
Ok(mastodon)
}
#[cfg(feature = "toml")]
2022-12-23 15:09:33 +00:00
pub fn read_line(message: impl AsRef<str>) -> Result<String> {
println!("{}", message.as_ref());
2022-11-27 14:44:43 +00:00
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}
#[cfg(feature = "toml")]
pub fn bool_input(message: impl AsRef<str>, default: bool) -> Result<bool> {
let input = read_line(message.as_ref())?;
if let Some(first_char) = input.chars().next() {
match first_char {
'Y' | 'y' => Ok(true),
'N' | 'n' => Ok(false),
'\n' => Ok(default),
_ => {
print!(
"I didn't understand '{input}'. Please input something that begins with 'y' \
or 'n', case insensitive: "
);
bool_input(message, default)
}
}
} else {
Ok(default)
}
}
2022-11-27 14:44:43 +00:00
#[cfg(not(feature = "toml"))]
fn main() {}