Merge branch 'tests' into develop

This commit is contained in:
Alie 2024-01-26 18:45:50 +01:00
commit 5fe0d6a269
7 changed files with 185 additions and 61 deletions

View File

@ -30,3 +30,5 @@
/target /target
LICENSE LICENSE
README.md README.md
config.toml
mastodon-data.toml

2
.gitignore vendored
View File

@ -3,4 +3,4 @@ mastodon-data.toml
*.csv *.csv
*.tmp *.tmp
*.log *.log
tmp/ tmp/

View File

@ -3,6 +3,9 @@ name = "mastodon-image-uploader-bot"
version = "0.2.2" version = "0.2.2"
edition = "2021" edition = "2021"
[alias]
test = "cargo test -- --test-threads=1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]

View File

@ -15,7 +15,7 @@ WORKDIR /app
# Build the application. # Build the application.
# Leverage a cache mount to /usr/local/cargo/registry/ # Leverage a cache mount to /usr/local/cargo/registry/
# for downloaded dependencies and a cache mount to /app/target/ for # for downloaded dependencies and a cache mount to /app/target/ for
# compiled dependencies which will speed up subsequent builds. # compiled dependencies which will speed up subsequent builds.
# Leverage a bind mount to the src directory to avoid having to copy the # Leverage a bind mount to the src directory to avoid having to copy the
# source code into the container. Once built, copy the executable to an # source code into the container. Once built, copy the executable to an
@ -59,4 +59,4 @@ USER botuser
COPY --from=build /bin/bot /bin/ COPY --from=build /bin/bot /bin/
# What the container should run when it is started. # What the container should run when it is started.
CMD ["/bin/cd", "/bin/bot"] CMD ["/bin/bot"]

View File

@ -6,8 +6,9 @@ bio = "Bot who posts images of sleeping girls every 6 hours."
[files] [files]
urls = "./urls.csv" urls = "./urls.csv"
posted = "./posted.csv" posted = "./posted.csv"
tempfile = ".tmp" tempfile = "/tmp/botimage.png"
[errors] [errors]
out_of_images = "@Sugui@awoo.fai.st @MeDueleLaTeta@awoo.fai.st me quedé sin chicas" maintainers = "@Sugui@awoo.fai.st @MeDueleLaTeta@awoo.fai.st"
retry = 10 out_of_images = "me quedé sin chicas"
retry = 10

View File

@ -11,20 +11,18 @@ spec:
containers: containers:
- name: bot-job - name: bot-job
image: git.fai.st/fedi-image-bot/mastodon-image-uploader-bot:latest image: git.fai.st/fedi-image-bot/mastodon-image-uploader-bot:latest
# Command to execute your Rust application or script
command: ["/path/to/your/rust/executable"]
volumeMounts: volumeMounts:
- name: config-toml - name: config-toml
mountPath: /botuser/ mountPath: /app/
readOnly: true readOnly: true
- name: mastodon-token - name: mastodon-token
mountPath: /botuser/ mountPath: /app/
readOnly: true readOnly: true
restartPolicy: Never restartPolicy: Never
volumes: volumes:
- name: config-volume - name: config-toml
configMap: configMap:
name: my-config name: bot-config-toml
- name: mastodon-token - name: mastodon-token
secret: secret:
secretName: mastodon-data secretName: mastodon-data

View File

@ -1,5 +1,5 @@
use async_std; use async_std;
use log; use log::{self, info};
use mastodon_async::entities::visibility::Visibility; use mastodon_async::entities::visibility::Visibility;
use mastodon_async::helpers::{cli, toml as masto_toml}; use mastodon_async::helpers::{cli, toml as masto_toml};
use mastodon_async::prelude::*; use mastodon_async::prelude::*;
@ -43,6 +43,7 @@ struct Files {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Errors { struct Errors {
maintainers: String,
out_of_images: String, out_of_images: String,
retry: u8, retry: u8,
} }
@ -55,44 +56,25 @@ async fn main() -> DynResult<()> {
.verbosity(4) // Debug .verbosity(4) // Debug
.timestamp(stderrlog::Timestamp::Second) .timestamp(stderrlog::Timestamp::Second)
.init()?; .init()?;
let config: Config = match parse_config(CONFIG_FILENAME) {
Ok(config) => config,
Err(err) => {
log::error!("Config file parsing unsuccesful: {}", err);
exit(1);
}
};
let mastodon = if let Ok(data) = masto_toml::from_file("mastodon-data.toml") { let config: Config = get_config();
Mastodon::from(data) let mastodon = get_account(&config).await;
} else {
match register(&config).await {
Ok(account) => account,
Err(err) => {
log::error!("Api registation unsuccesful: {}", err);
exit(1);
}
}
};
match get_next_url(&config) { match get_next_url(&config) {
Ok(url) => match url { Ok(url) => match url {
Some(url) => { Some(url) => {
let mut retry: u8 = 0; let mut retry: u8 = 0;
while let Err(err) = post_image(&mastodon, &url, &config).await { while let Err(err) = post_image(&mastodon, &url, &config, Visibility::Unlisted).await {
log::warn!("Cannot post image, retry: {}, {}", retry, err); log::warn!("Cannot post image, retry: {}, {}", retry, err);
async_std::task::sleep(Duration::new(1, 0)).await; async_std::task::sleep(Duration::new(1, 0)).await;
retry += 1; retry += 1;
if retry >= config.errors.retry { if retry >= config.errors.retry {
log::error!("Max ammount of retries reached on post_image"); log::error!("Max ammount of retries reached on post_image");
log::info!("Reverting file changes"); log::info!("Reverting file changes");
while let Err(err) = pop_last_line_of_file(&config.files.posted) {
log::warn!("Failed to revert, retrying: {}", err);
async_std::task::sleep(Duration::new(1, 0)).await;
}
exit(1); exit(1);
} }
} }
set_url_as_posted(&config, &url)?;
let mut retry: u8 = 0; let mut retry: u8 = 0;
while let Err(err) = update_bio(&mastodon, &config).await { while let Err(err) = update_bio(&mastodon, &config).await {
log::warn!("Cannot update bio, retry: {}, {}", retry, err); log::warn!("Cannot update bio, retry: {}, {}", retry, err);
@ -106,7 +88,16 @@ async fn main() -> DynResult<()> {
} }
None => { None => {
let mut retry: u8 = 0; let mut retry: u8 = 0;
while let Err(err) = post(&mastodon, &config.errors.out_of_images).await { while let Err(err) = post(
&mastodon,
&format!(
"{} {}",
&config.errors.maintainers, &config.errors.out_of_images
),
Visibility::Direct,
)
.await
{
log::warn!("Cannot post, retry: {}, {}", retry, err); log::warn!("Cannot post, retry: {}, {}", retry, err);
async_std::task::sleep(Duration::new(1, 0)).await; async_std::task::sleep(Duration::new(1, 0)).await;
retry += 1; retry += 1;
@ -119,7 +110,13 @@ async fn main() -> DynResult<()> {
}, },
Err(err) => { Err(err) => {
log::error!("Cannot get next image: {}", err); log::error!("Cannot get next image: {}", err);
match post(&mastodon, &err.to_string()).await { match post(
&mastodon,
&format!("{} {}", &config.errors.maintainers, &err.to_string()),
Visibility::Direct,
)
.await
{
Ok(_) => {} Ok(_) => {}
Err(err) => { Err(err) => {
log::error!("Cannot post error message: {}", err); log::error!("Cannot post error message: {}", err);
@ -131,21 +128,36 @@ async fn main() -> DynResult<()> {
Ok(()) 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);
}
}
}
}
/// Parses the given filename to a config struct /// Parses the given filename to a config struct
fn parse_config(filename: &str) -> DynResult<Config> { 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"); 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") Ok(toml::from_str(&toml_file)?) //("Malformed config file, check the original one for reference")
} }
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");
Ok(())
}
fn get_next_url(config: &Config) -> DynResult<Option<String>> { fn get_next_url(config: &Config) -> DynResult<Option<String>> {
let binding = std::fs::read_to_string(&config.files.posted)?; //.expect("Posted file not found"); let binding = std::fs::read_to_string(&config.files.posted)?; //.expect("Posted file not found");
let posted = binding.lines().collect::<HashSet<&str>>(); let posted = binding.lines().collect::<HashSet<&str>>();
@ -155,16 +167,26 @@ fn get_next_url(config: &Config) -> DynResult<Option<String>> {
if urls.is_empty() { if urls.is_empty() {
Ok(None) Ok(None)
} else { } else {
let mut file = std::fs::OpenOptions::new()
.write(true)
.append(true) // This is needed to append to file
.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())) Ok(Some(urls[0].to_string().clone()))
} }
} }
async fn post_image(account: &Mastodon, url: &String, config: &Config) -> DynResult<()> { fn set_url_as_posted(config: &Config, url: &String) -> DynResult<()> {
let mut file = std::fs::OpenOptions::new()
.write(true)
.append(true) // This is needed to append to file
.open(&config.files.posted)?; //.expect("Cannot open posted file"); // Maybe we should retry just in case
write!(file, "{}\n", url)?; //.expect("Cannot write to posted file"); // maybe we should retry tbh
info!("Set url {} as posted", url);
Ok(())
}
async fn post_image(
account: &Mastodon,
url: &String,
config: &Config,
visibility: Visibility,
) -> DynResult<Status> {
fetch_url(url, &config.files.tempfile).await?; //.expect("Error fetching url"); fetch_url(url, &config.files.tempfile).await?; //.expect("Error fetching url");
let attachment = account let attachment = account
.media(&config.files.tempfile, Some(url.to_string())) .media(&config.files.tempfile, Some(url.to_string()))
@ -174,12 +196,12 @@ async fn post_image(account: &Mastodon, url: &String, config: &Config) -> DynRes
.await?; //.expect("Attachment processing error"); .await?; //.expect("Attachment processing error");
let status = StatusBuilder::new() let status = StatusBuilder::new()
.media_ids(&[attachment.id]) .media_ids(&[attachment.id])
.visibility(Visibility::Unlisted) .visibility(visibility)
.sensitive(true) .sensitive(true)
.build()?; //.expect("Could not build status"); // we should retry .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 let status = account.new_status(status).await?; //.expect("Error generating status"); // we should retry or delete last url in posted
log::info!("Image status posted: {}", url); log::info!("Image status posted: {}", url);
Ok(()) Ok(status)
} }
async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> { async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> {
@ -208,14 +230,14 @@ async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> {
Ok(()) Ok(())
} }
async fn post(account: &Mastodon, msg: &str) -> DynResult<()> { async fn post(account: &Mastodon, msg: &str, visibility: Visibility) -> DynResult<Status> {
let status = StatusBuilder::new() let status = StatusBuilder::new()
.visibility(Visibility::Direct) .visibility(visibility)
.status(msg) .status(msg)
.build()?; //.expect("Error building error status"); .build()?; //.expect("Error building error status");
account.new_status(status).await?; //.expect("Error posting error status"); let post = account.new_status(status).await?; //.expect("Error posting error status");
log::info!("Text status posted: {}", msg); log::info!("Text status posted: {}", msg);
Ok(()) Ok(post)
} }
async fn fetch_url(url: &String, file_name: &String) -> DynResult<()> { async fn fetch_url(url: &String, file_name: &String) -> DynResult<()> {
@ -229,7 +251,7 @@ async fn fetch_url(url: &String, file_name: &String) -> DynResult<()> {
async fn register(config: &Config) -> DynResult<Mastodon> { async fn register(config: &Config) -> DynResult<Mastodon> {
let registration = Registration::new(&config.bot.instance) let registration = Registration::new(&config.bot.instance)
.client_name(&config.bot.name) .client_name(&config.bot.name)
.scopes(Scopes::write_all()) .scopes(Scopes::all())
.build() .build()
.await?; .await?;
let mastodon = cli::authenticate(registration).await?; let mastodon = cli::authenticate(registration).await?;
@ -239,3 +261,101 @@ async fn register(config: &Config) -> DynResult<Mastodon> {
Ok(mastodon) Ok(mastodon)
} }
#[cfg(test)]
mod tests {
use reqwest::StatusCode;
use super::*;
const TMPTESTDIR: &str = "/tmp/botimage";
const TEST_URL: &str = "https://2.gravatar.com/avatar/be8eb8426d68e4beb50790647eda6f6b";
#[tokio::test]
async fn fetch_url_should_fetch() {
fetch_url(&TEST_URL.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();
account.delete_status(&status.id).await.unwrap();
assert_eq!(response.status(), StatusCode::OK)
}
#[tokio::test]
async fn post_image_works() {
let client = reqwest::Client::new();
let config = get_config();
let account = get_account(&config).await;
let status = post_image(&account, &TEST_URL.to_string(), &config, Visibility::Direct)
.await
.unwrap();
let response = account.get_status(&status.id).await.unwrap();
account.delete_status(&status.id).await.unwrap();
let attachment = &response.media_attachments[0];
let response = client
.get(attachment.url.clone().unwrap())
.bearer_auth(dbg!(&account.data.token))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK)
}
#[test]
fn set_as_posted_works() {
let config = get_config();
std::fs::write(&config.files.posted, "").unwrap();
set_url_as_posted(&config, &TEST_URL.to_string()).unwrap();
let file = std::fs::read_to_string(&config.files.posted).unwrap();
let url = file.lines().next_back().unwrap();
assert_eq!(url, TEST_URL)
}
#[test]
fn get_next_url_works() {
let config = get_config();
// Reset file
std::fs::write(&config.files.posted, "").unwrap();
// Get test url
let url = get_next_url(&config).unwrap().unwrap();
assert_eq!(url, TEST_URL);
set_url_as_posted(&config, &TEST_URL.to_string()).unwrap();
let file = std::fs::read_to_string(&config.files.posted).unwrap();
let url = file.lines().next_back().unwrap();
assert_eq!(url, TEST_URL);
// Test that now it does not get it
let url = get_next_url(&config).unwrap();
assert_eq!(url, None);
}
}