bot-mastodon-image-uploader/src/main.rs

308 lines
9.0 KiB
Rust
Raw Normal View History

2023-07-19 07:38:49 +00:00
use async_std;
use log;
2023-07-14 08:17:36 +00:00
use mastodon_async::entities::visibility::Visibility;
2023-07-14 17:04:58 +00:00
use mastodon_async::helpers::{cli, toml as masto_toml};
2023-07-14 08:17:36 +00:00
use mastodon_async::prelude::*;
2023-02-22 18:33:39 +00:00
use reqwest;
2023-07-19 08:57:22 +00:00
use serde::{Deserialize, Serialize};
2023-07-14 08:17:36 +00:00
use std::collections::HashSet;
2023-07-14 17:04:58 +00:00
use std::io::{Cursor, Write};
use std::process::exit;
2023-07-19 07:38:49 +00:00
use std::time::Duration;
2023-07-14 08:17:36 +00:00
use toml;
2023-07-14 17:04:58 +00:00
2023-07-19 08:57:22 +00:00
#[derive(Debug, Serialize)]
struct AccountUpdate {
note: String,
}
2023-07-14 08:17:36 +00:00
const CONFIG_FILENAME: &str = "config.toml";
2023-07-19 07:38:49 +00:00
type DynResult<T> = Result<T, Box<dyn std::error::Error>>;
2023-07-14 17:04:58 +00:00
2023-07-14 08:17:36 +00:00
#[derive(Deserialize)]
struct Config {
bot: Bot,
files: Files,
errors: Errors,
}
#[derive(Deserialize)]
struct Bot {
name: String,
instance: String,
bio: String,
}
#[derive(Deserialize)]
struct Files {
posted: String,
urls: String,
tempfile: String,
}
#[derive(Deserialize)]
struct Errors {
maintainers: String,
2023-07-14 08:17:36 +00:00
out_of_images: String,
2023-07-14 17:04:58 +00:00
retry: u8,
2023-07-14 08:17:36 +00:00
}
2023-02-22 18:33:39 +00:00
#[tokio::main] // requires `features = ["mt"]
2023-07-14 17:04:58 +00:00
async fn main() -> DynResult<()> {
stderrlog::new()
.module(module_path!())
.quiet(false)
.verbosity(4) // Debug
.timestamp(stderrlog::Timestamp::Second)
.init()?;
let config: Config = get_config();
let mastodon = get_account(&config).await;
2023-02-22 18:33:39 +00:00
2023-07-14 08:17:36 +00:00
match get_next_url(&config) {
2023-07-14 17:04:58 +00:00
Ok(url) => match url {
Some(url) => {
let mut retry: u8 = 0;
while let Err(err) = post_image(&mastodon, &url, &config).await {
log::warn!("Cannot post image, retry: {}, {}", retry, err);
2023-07-19 07:38:49 +00:00
async_std::task::sleep(Duration::new(1, 0)).await;
2023-07-14 17:04:58 +00:00
retry += 1;
if retry >= config.errors.retry {
log::error!("Max ammount of retries reached on post_image");
log::info!("Reverting file changes");
while let Err(err) = pop_last_line_of_file(&config.files.posted) {
log::warn!("Failed to revert, retrying: {}", err);
2023-07-19 07:38:49 +00:00
async_std::task::sleep(Duration::new(1, 0)).await;
2023-07-14 17:04:58 +00:00
}
exit(1);
}
}
let mut retry: u8 = 0;
while let Err(err) = update_bio(&mastodon, &config).await {
log::warn!("Cannot update bio, retry: {}, {}", retry, err);
2023-07-19 07:38:49 +00:00
async_std::task::sleep(Duration::new(1, 0)).await;
2023-07-14 17:04:58 +00:00
retry += 1;
if retry >= config.errors.retry {
log::error!("Max ammount of retries reached on update bio");
exit(1);
}
}
}
None => {
let mut retry: u8 = 0;
while let Err(err) = post(
&mastodon,
&format!(
"{}{}",
&config.errors.maintainers, &config.errors.out_of_images
),
Visibility::Direct,
)
.await
{
2023-07-14 17:04:58 +00:00
log::warn!("Cannot post, retry: {}, {}", retry, err);
async_std::task::sleep(Duration::new(1, 0)).await;
2023-07-14 17:04:58 +00:00
retry += 1;
if retry >= config.errors.retry {
log::error!("Max ammount of retries reached on post");
exit(1);
}
}
}
},
Err(err) => {
log::error!("Cannot get next image: {}", err);
match post(
&mastodon,
&format!("{}{}", &config.errors.maintainers, &err.to_string()),
Visibility::Direct,
)
.await
{
2023-07-14 17:04:58 +00:00
Ok(_) => {}
Err(err) => {
log::error!("Cannot post error message: {}", err);
exit(1);
}
};
2023-02-22 18:33:39 +00:00
}
2023-07-14 17:04:58 +00:00
}
Ok(())
}
fn get_config() -> Config {
match parse_config(CONFIG_FILENAME) {
Ok(config) => config,
Err(err) => {
log::error!("Config file parsing unsuccesful: {}", err);
exit(1);
}
}
}
async fn get_account(config: &Config) -> Mastodon {
if let Ok(data) = masto_toml::from_file("mastodon-data.toml") {
Mastodon::from(data)
} else {
match register(config).await {
Ok(account) => account,
Err(err) => {
log::error!("Api registation unsuccesful: {}", err);
exit(1);
}
}
}
}
2023-07-14 17:04:58 +00:00
/// Parses the given filename to a config struct
fn parse_config(filename: &str) -> DynResult<Config> {
let toml_file = std::fs::read_to_string(filename)?; //.expect("No config file, consider getting the original one and modifing it");
Ok(toml::from_str(&toml_file)?) //("Malformed config file, check the original one for reference")
}
2023-07-14 08:17:36 +00:00
2023-07-14 17:04:58 +00:00
fn pop_last_line_of_file(filename: &str) -> DynResult<()> {
let binding = std::fs::read_to_string(filename)?;
let mut posted: Vec<_> = binding.lines().collect();
posted.pop();
std::fs::write(filename, posted.concat())?;
log::info!("Success reverting changes");
2023-07-14 08:17:36 +00:00
Ok(())
2023-02-22 18:33:39 +00:00
}
2023-07-14 17:04:58 +00:00
fn get_next_url(config: &Config) -> DynResult<Option<String>> {
let binding = std::fs::read_to_string(&config.files.posted)?; //.expect("Posted file not found");
2023-07-14 08:17:36 +00:00
let posted = binding.lines().collect::<HashSet<&str>>();
2023-07-14 17:04:58 +00:00
let binding = std::fs::read_to_string(&config.files.urls)?; //.expect("Urls file not found");
2023-07-14 08:17:36 +00:00
let urls = binding.lines().collect::<HashSet<&str>>();
let urls = urls.difference(&posted).collect::<Vec<_>>();
if urls.is_empty() {
2023-07-14 17:04:58 +00:00
Ok(None)
2023-07-14 08:17:36 +00:00
} else {
let mut file = std::fs::OpenOptions::new()
.write(true)
.append(true) // This is needed to append to file
2023-07-14 17:04:58 +00:00
.open(&config.files.posted)?; //.expect("Cannot open posted file"); // Maybe we should retry just in case
write!(file, "{}\n", urls[0])?; //.expect("Cannot write to posted file"); // maybe we should retry tbh
Ok(Some(urls[0].to_string().clone()))
2023-07-14 08:17:36 +00:00
}
}
2023-03-09 19:23:56 +00:00
2023-07-14 17:04:58 +00:00
async fn post_image(account: &Mastodon, url: &String, config: &Config) -> DynResult<()> {
fetch_url(url, &config.files.tempfile).await?; //.expect("Error fetching url");
2023-07-14 08:17:36 +00:00
let attachment = account
.media(&config.files.tempfile, Some(url.to_string()))
2023-07-14 17:04:58 +00:00
.await?; //.expect("Attachment upload error");
2023-07-14 08:17:36 +00:00
let attachment = account
.wait_for_processing(attachment, Default::default())
2023-07-14 17:04:58 +00:00
.await?; //.expect("Attachment processing error");
2023-07-14 08:17:36 +00:00
let status = StatusBuilder::new()
.media_ids(&[attachment.id])
.visibility(Visibility::Unlisted)
.sensitive(true)
2023-07-14 17:04:58 +00:00
.build()?; //.expect("Could not build status"); // we should retry
account.new_status(status).await?; //.expect("Error generating status"); // we should retry or delete last url in posted
log::info!("Image status posted: {}", url);
Ok(())
2023-03-09 19:23:56 +00:00
}
2023-07-14 17:04:58 +00:00
async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> {
let binding = std::fs::read_to_string(&config.files.posted)?; //.expect("Posted file not found");
2023-07-14 08:17:36 +00:00
let posted = binding.lines().collect::<HashSet<&str>>();
2023-07-14 17:04:58 +00:00
let binding = std::fs::read_to_string(&config.files.urls)?; //.expect("Url file not found");
2023-07-14 08:17:36 +00:00
let urls = binding.lines().collect::<HashSet<&str>>();
let remaining = urls.difference(&posted).count();
let client = reqwest::Client::new();
2023-07-19 08:57:22 +00:00
let account_update = AccountUpdate {
note: format!("{}\n\n{} new images remaining", config.bot.bio, remaining),
};
let response = client
.patch(&format!(
"{}/api/v1/accounts/update_credentials",
config.bot.instance
))
.bearer_auth(&account.data.token)
2023-07-19 08:57:22 +00:00
.json(&account_update)
.send()
.await?;
log::info!("Bio updated, response status: {}", response.status());
2023-07-14 17:04:58 +00:00
Ok(())
2023-02-22 18:33:39 +00:00
}
async fn post(account: &Mastodon, msg: &str, visibility: Visibility) -> DynResult<Status> {
2023-07-14 08:17:36 +00:00
let status = StatusBuilder::new()
.visibility(visibility)
2023-02-22 18:33:39 +00:00
.status(msg)
2023-07-14 17:04:58 +00:00
.build()?; //.expect("Error building error status");
let post = account.new_status(status).await?; //.expect("Error posting error status");
2023-07-14 17:04:58 +00:00
log::info!("Text status posted: {}", msg);
Ok(post)
2023-02-22 18:33:39 +00:00
}
async fn fetch_url(url: &String, file_name: &String) -> DynResult<()> {
2023-07-14 17:04:58 +00:00
let response = reqwest::get(url);
2023-07-14 08:17:36 +00:00
let mut file = std::fs::File::create(file_name)?;
2023-07-14 17:04:58 +00:00
let mut content = Cursor::new(response.await?.bytes().await?);
2023-07-14 08:17:36 +00:00
std::io::copy(&mut content, &mut file)?;
Ok(())
2023-02-22 18:33:39 +00:00
}
2023-07-19 07:38:49 +00:00
async fn register(config: &Config) -> DynResult<Mastodon> {
2023-07-14 08:17:36 +00:00
let registration = Registration::new(&config.bot.instance)
.client_name(&config.bot.name)
.scopes(Scopes::all())
2023-07-14 08:17:36 +00:00
.build()
.await?;
let mastodon = cli::authenticate(registration).await?;
2023-02-22 18:33:39 +00:00
2023-07-14 08:17:36 +00:00
// Save app data for using on the next run.
masto_toml::to_file(&mastodon.data, "mastodon-data.toml")?;
2023-02-22 18:33:39 +00:00
2023-07-14 08:17:36 +00:00
Ok(mastodon)
2023-02-22 18:33:39 +00:00
}
2024-01-21 16:23:43 +00:00
#[cfg(test)]
mod tests {
use reqwest::StatusCode;
use super::*;
const TMPTESTDIR: &str = "/tmp/botimage";
#[tokio::test]
async fn fetch_url_should_fetch() {
fetch_url(
&"https://2.gravatar.com/avatar/be8eb8426d68e4beb50790647eda6f6b".to_string(),
&TMPTESTDIR.to_string(),
)
.await
.unwrap();
std::fs::read(TMPTESTDIR).unwrap();
}
#[tokio::test]
async fn post_should_post() {
let client = reqwest::Client::new();
let config = get_config();
let account = get_account(&config).await;
let msg = format!("Test!");
let status = post(&account, &msg, Visibility::Direct).await.unwrap();
let response = client
.get(dbg!(format!(
"{}/api/v1/statuses/{}",
&config.bot.instance,
&status.id.to_string()
)))
.bearer_auth(dbg!(&account.data.token))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK)
}
}