Compare commits
20 Commits
Author | SHA1 | Date |
---|---|---|
Renovate Bot | 926959fa7e | |
bizcochito | 94e3f53d19 | |
Renovate Bot | e83b20081b | |
Renovate Bot | 3a7a39d170 | |
bizcochito | 22e2dd92e6 | |
bizcochito | cffc5e04e0 | |
Renovate Bot | 1a384cfdfe | |
bizcochito | 27f0b1bfe6 | |
Renovate Bot | a2aa2654ff | |
bizcochito | d50c1d7e61 | |
bizcochito | 9aa7be030a | |
Renovate Bot | f4e463abc1 | |
Renovate Bot | 5d91a9979e | |
Alie | 9b9ddc1d42 | |
Alie | e9d332487d | |
Alie | 64a5ebca2f | |
Alie | 079ad337ca | |
Alie | 34d902cfc8 | |
Alie | 467027fffe | |
Sugui | 197743889d |
|
@ -43,7 +43,7 @@ jobs:
|
||||||
username: ${{ secrets.DOCKER_USER }}
|
username: ${{ secrets.DOCKER_USER }}
|
||||||
password: ${{ secrets.DOCKER_PASS }}
|
password: ${{ secrets.DOCKER_PASS }}
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@48aba3b46d1b1fec4febb7c5d0c644b249a11355 # v6
|
uses: docker/build-push-action@ca877d9245402d1537745e0e356eab47c3520991 # v6
|
||||||
with:
|
with:
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
context: .
|
context: .
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
13
Cargo.toml
13
Cargo.toml
|
@ -6,14 +6,9 @@ edition = "2021"
|
||||||
# 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]
|
||||||
tokio = { version = "=1.42.0", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "=1.43.0", features = ["macros", "rt-multi-thread"] }
|
||||||
reqwest = { version = "=0.11.27", features = ["json"] }
|
reqwest = { version = "=0.12.12", features = ["json", "multipart", "stream"] }
|
||||||
serde = "=1.0.217"
|
serde = { version = "=1.0.217", features = ["derive"] }
|
||||||
toml = "=0.8.19"
|
toml = "=0.8.19"
|
||||||
log = "=0.4.22"
|
log = "=0.4.25"
|
||||||
stderrlog = "=0.6.0"
|
stderrlog = "=0.6.0"
|
||||||
async-std = "=1.13.0"
|
|
||||||
|
|
||||||
[dependencies.mastodon-async]
|
|
||||||
version = "=1.3.2"
|
|
||||||
features = ["toml", "mt"]
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
FROM rust:1.83.0-slim-bullseye AS deps
|
FROM rust:1.84.0-slim-bullseye AS deps
|
||||||
RUN apt update && apt install pkg-config ca-certificates openssl libssl-dev -y
|
RUN apt update && apt install pkg-config ca-certificates openssl libssl-dev -y
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY Cargo.toml Cargo.toml
|
COPY Cargo.toml Cargo.toml
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
db = new Mongo().getDB("bot");
|
db = new Mongo().getDB("bot");
|
||||||
|
|
||||||
db.createCollection('authorizations');
|
db.createCollection("authorizations");
|
||||||
|
|
||||||
db.authorizations.insert([
|
db.authorizations.insert([
|
||||||
{
|
{
|
||||||
app: "tester",
|
app: "tester",
|
||||||
secret: "test",
|
secret: "test",
|
||||||
}
|
},
|
||||||
]);
|
]);
|
|
@ -1,5 +1,6 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||||
"extends": ["config:recommended", "helpers:pinGitHubActionDigests"],
|
"extends": ["config:recommended", "helpers:pinGitHubActionDigests"],
|
||||||
"rangeStrategy": "pin"
|
"rangeStrategy": "pin",
|
||||||
|
"automerge": true
|
||||||
}
|
}
|
369
src/main.rs
369
src/main.rs
|
@ -1,6 +1,4 @@
|
||||||
use mastodon_async::entities::visibility::Visibility;
|
use reqwest::Client;
|
||||||
use mastodon_async::helpers::{cli, toml as masto_toml};
|
|
||||||
use mastodon_async::prelude::*;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
use std::process::exit;
|
use std::process::exit;
|
||||||
|
@ -29,6 +27,7 @@ struct AccountUpdate {
|
||||||
}
|
}
|
||||||
|
|
||||||
const CONFIG_FILENAME: &str = "config.toml";
|
const CONFIG_FILENAME: &str = "config.toml";
|
||||||
|
const CREDENTIALS_FILENAME: &str = "mastodon-data.toml";
|
||||||
|
|
||||||
type DynResult<T> = Result<T, Box<dyn std::error::Error>>;
|
type DynResult<T> = Result<T, Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
@ -66,7 +65,7 @@ struct Errors {
|
||||||
retry: u8,
|
retry: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main] // requires `features = ["mt"]
|
#[tokio::main]
|
||||||
async fn main() -> DynResult<()> {
|
async fn main() -> DynResult<()> {
|
||||||
stderrlog::new()
|
stderrlog::new()
|
||||||
.module(module_path!())
|
.module(module_path!())
|
||||||
|
@ -75,17 +74,22 @@ async fn main() -> DynResult<()> {
|
||||||
.timestamp(stderrlog::Timestamp::Second)
|
.timestamp(stderrlog::Timestamp::Second)
|
||||||
.init()?;
|
.init()?;
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("bot")
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
let config: Config = get_config();
|
let config: Config = get_config();
|
||||||
let mastodon = get_account(&config).await;
|
let creds = get_mastodon_data(&client, &config).await;
|
||||||
|
|
||||||
match get_next_url(&config).await {
|
match get_next_url(&config).await {
|
||||||
Ok(image) => match image {
|
Ok(image) => match image {
|
||||||
Some(image) => {
|
Some(image) => {
|
||||||
let mut retry: u8 = 0;
|
let mut retry: u8 = 0;
|
||||||
while let Err(err) = post_image(&mastodon, &image.url, &config, Visibility::Unlisted).await
|
while let Err(err) =
|
||||||
|
post_image(&client, &creds, &config, &image.url, Visibility::public).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;
|
std::thread::sleep(Duration::new(1, 0));
|
||||||
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");
|
||||||
|
@ -95,9 +99,9 @@ async fn main() -> DynResult<()> {
|
||||||
}
|
}
|
||||||
set_url_as_posted(&config, &image).await?;
|
set_url_as_posted(&config, &image).await?;
|
||||||
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(&config, &creds).await {
|
||||||
log::warn!("Cannot update bio, retry: {}, {}", retry, err);
|
log::warn!("Cannot update bio, retry: {}, {}", retry, err);
|
||||||
async_std::task::sleep(Duration::new(1, 0)).await;
|
std::thread::sleep(Duration::new(1, 0));
|
||||||
retry += 1;
|
retry += 1;
|
||||||
if retry >= config.errors.retry {
|
if retry >= config.errors.retry {
|
||||||
log::error!("Max ammount of retries reached on update bio");
|
log::error!("Max ammount of retries reached on update bio");
|
||||||
|
@ -108,17 +112,19 @@ async fn main() -> DynResult<()> {
|
||||||
None => {
|
None => {
|
||||||
let mut retry: u8 = 0;
|
let mut retry: u8 = 0;
|
||||||
while let Err(err) = post(
|
while let Err(err) = post(
|
||||||
&mastodon,
|
&client,
|
||||||
|
&creds,
|
||||||
|
&config,
|
||||||
&format!(
|
&format!(
|
||||||
"{} {}",
|
"{} {}",
|
||||||
&config.errors.maintainers, &config.errors.out_of_images
|
&config.errors.maintainers, &config.errors.out_of_images
|
||||||
),
|
),
|
||||||
Visibility::Direct,
|
Visibility::direct,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
log::warn!("Cannot post, retry: {}, {}", retry, err);
|
log::warn!("Cannot post, retry: {}, {}", retry, err);
|
||||||
async_std::task::sleep(Duration::new(1, 0)).await;
|
std::thread::sleep(Duration::new(1, 0));
|
||||||
retry += 1;
|
retry += 1;
|
||||||
if retry >= config.errors.retry {
|
if retry >= config.errors.retry {
|
||||||
log::error!("Max ammount of retries reached on post");
|
log::error!("Max ammount of retries reached on post");
|
||||||
|
@ -130,9 +136,11 @@ async fn main() -> DynResult<()> {
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::error!("Cannot get next image: {}", err);
|
log::error!("Cannot get next image: {}", err);
|
||||||
match post(
|
match post(
|
||||||
&mastodon,
|
&client,
|
||||||
|
&creds,
|
||||||
|
&config,
|
||||||
&format!("{} {}", &config.errors.maintainers, &err.to_string()),
|
&format!("{} {}", &config.errors.maintainers, &err.to_string()),
|
||||||
Visibility::Direct,
|
Visibility::direct,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
|
@ -166,24 +174,9 @@ fn generate_config() -> DynResult<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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)?;
|
||||||
Ok(toml::from_str(&toml_file)?) //("Malformed config file, check the original one for reference")
|
Ok(toml::from_str(&toml_file)?)
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_account(config: &Config) -> Mastodon {
|
|
||||||
if let Ok(data) = masto_toml::from_file("mastodon-data.toml") {
|
|
||||||
Mastodon::new(reqwest::Client::builder().user_agent("bot").build().unwrap(), data)
|
|
||||||
} else {
|
|
||||||
match register(config).await {
|
|
||||||
Ok(account) => account,
|
|
||||||
Err(err) => {
|
|
||||||
log::error!("Api registation unsuccesful: {}", err);
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_next_url(config: &Config) -> DynResult<Option<Image>> {
|
async fn get_next_url(config: &Config) -> DynResult<Option<Image>> {
|
||||||
|
@ -216,7 +209,10 @@ struct Token {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn set_url_as_posted(config: &Config, image: &Image) -> DynResult<()> {
|
async fn set_url_as_posted(config: &Config, image: &Image) -> DynResult<()> {
|
||||||
let client = reqwest::Client::builder().user_agent("bot").build().unwrap();
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("bot")
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let auth = &Auth {
|
let auth = &Auth {
|
||||||
app: config.backend.app.to_string(),
|
app: config.backend.app.to_string(),
|
||||||
|
@ -250,36 +246,37 @@ async fn set_url_as_posted(config: &Config, image: &Image) -> DynResult<()> {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn post_image(
|
async fn post_image(
|
||||||
account: &Mastodon,
|
client: &Client,
|
||||||
url: &String,
|
creds: &MastodonData,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
|
url: &String,
|
||||||
visibility: Visibility,
|
visibility: Visibility,
|
||||||
) -> DynResult<Status> {
|
) -> DynResult<Post> {
|
||||||
fetch_url(url, &config.files.tempfile).await?; //.expect("Error fetching url");
|
fetch_url(url, &config.files.tempfile).await?;
|
||||||
let attachment = account
|
let media_id = upload_media(&client, &creds, &config, url).await?.id;
|
||||||
.media(&config.files.tempfile, Some(url.to_string()))
|
let post = PostForm {
|
||||||
.await?; //.expect("Attachment upload error");
|
media_ids: vec![media_id],
|
||||||
let attachment = account
|
sensitive: true,
|
||||||
.wait_for_processing(attachment, Default::default())
|
status: String::new(),
|
||||||
.await?; //.expect("Attachment processing error");
|
visibility,
|
||||||
let status = StatusBuilder::new()
|
};
|
||||||
.media_ids(&[attachment.id])
|
let status = post_status(&client, &creds, &config, post).await?;
|
||||||
.visibility(visibility)
|
|
||||||
.sensitive(true)
|
|
||||||
.build()?; //.expect("Could not build status"); // we should retry
|
|
||||||
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(status)
|
Ok(status)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> {
|
async fn update_bio(config: &Config, creds: &MastodonData) -> DynResult<()> {
|
||||||
let images: ImagesWrap = reqwest::get(format!("{}/images?status=available", config.backend.url))
|
let images: ImagesWrap =
|
||||||
|
reqwest::get(format!("{}/images?status=available", config.backend.url))
|
||||||
.await?
|
.await?
|
||||||
.json()
|
.json()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let remaining = images.images.len();
|
let remaining = images.images.len();
|
||||||
let client = reqwest::Client::builder().user_agent("bot").build().unwrap();
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("bot")
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let account_update = AccountUpdate {
|
let account_update = AccountUpdate {
|
||||||
note: format!("{}\n\n{} new images remaining", config.bot.bio, remaining),
|
note: format!("{}\n\n{} new images remaining", config.bot.bio, remaining),
|
||||||
|
@ -290,7 +287,7 @@ async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> {
|
||||||
"{}/api/v1/accounts/update_credentials",
|
"{}/api/v1/accounts/update_credentials",
|
||||||
config.bot.instance
|
config.bot.instance
|
||||||
))
|
))
|
||||||
.bearer_auth(&account.data.token)
|
.bearer_auth(&creds.token)
|
||||||
.json(&account_update)
|
.json(&account_update)
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
@ -298,12 +295,20 @@ async fn update_bio(account: &Mastodon, config: &Config) -> DynResult<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn post(account: &Mastodon, msg: &str, visibility: Visibility) -> DynResult<Status> {
|
async fn post(
|
||||||
let status = StatusBuilder::new()
|
client: &Client,
|
||||||
.visibility(visibility)
|
creds: &MastodonData,
|
||||||
.status(msg)
|
config: &Config,
|
||||||
.build()?; //.expect("Error building error status");
|
msg: &str,
|
||||||
let post = account.new_status(status).await?; //.expect("Error posting error status");
|
visibility: Visibility,
|
||||||
|
) -> DynResult<Post> {
|
||||||
|
let post = PostForm {
|
||||||
|
status: msg.to_owned(),
|
||||||
|
sensitive: false,
|
||||||
|
visibility,
|
||||||
|
media_ids: vec![],
|
||||||
|
};
|
||||||
|
let post = post_status(client, creds, config, post).await?;
|
||||||
log::info!("Text status posted: {}", msg);
|
log::info!("Text status posted: {}", msg);
|
||||||
Ok(post)
|
Ok(post)
|
||||||
}
|
}
|
||||||
|
@ -316,27 +321,188 @@ async fn fetch_url(url: &String, file_name: &String) -> DynResult<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn register(config: &Config) -> DynResult<Mastodon> {
|
#[derive(Deserialize, Serialize)]
|
||||||
let registration = Registration::new_with_client(&config.bot.instance, reqwest::Client::builder().user_agent("bot").build().unwrap())
|
struct MastodonData {
|
||||||
.client_name(&config.bot.name)
|
base: String,
|
||||||
.scopes(Scopes::all())
|
client_id: String,
|
||||||
.build()
|
client_secret: String,
|
||||||
|
redirect: String,
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_mastodon_data(client: &Client, config: &Config) -> MastodonData {
|
||||||
|
match parse_mastodon_data(CREDENTIALS_FILENAME) {
|
||||||
|
Ok(config) => config,
|
||||||
|
Err(err) => {
|
||||||
|
log::error!("Credentials file parsing unsuccesful: {}", err);
|
||||||
|
register(client, config).await;
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct AppRegister {
|
||||||
|
client_id: String,
|
||||||
|
client_secret: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn register(client: &Client, config: &Config) {
|
||||||
|
let request = vec![
|
||||||
|
("client_name", config.bot.name.as_str()),
|
||||||
|
("redirect_uris", "urn:ietf:wg:oauth:2.0:oob"),
|
||||||
|
("scopes", "write"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let app: AppRegister = client
|
||||||
|
.post(format!("{}/api/v1/apps", config.bot.instance))
|
||||||
|
.form(&request)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("Error sending request to instance on app register")
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.expect("Error parsing app register response");
|
||||||
|
|
||||||
|
println!("Please enter into the following url to authrise:");
|
||||||
|
println!("{}/oauth/authorize?client_id={}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=write", config.bot.instance, app.client_id);
|
||||||
|
let mut token = String::new();
|
||||||
|
std::io::stdin()
|
||||||
|
.read_line(&mut token)
|
||||||
|
.expect("Error reading stdin");
|
||||||
|
|
||||||
|
let toml = toml::to_string(&MastodonData {
|
||||||
|
base: config.bot.instance.clone(),
|
||||||
|
client_id: app.client_id,
|
||||||
|
client_secret: app.client_secret,
|
||||||
|
redirect: "urn:ietf:wg:oauth:2.0:oob".to_string(),
|
||||||
|
token,
|
||||||
|
})
|
||||||
|
.expect("Failed to create credentials file");
|
||||||
|
|
||||||
|
std::fs::write(CREDENTIALS_FILENAME, toml).expect("Failed to write credentials file");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_mastodon_data(filename: &str) -> DynResult<MastodonData> {
|
||||||
|
let toml_file = std::fs::read_to_string(filename)?;
|
||||||
|
Ok(toml::from_str(&toml_file)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct Post {
|
||||||
|
id: String,
|
||||||
|
media_attachments: Vec<Attachment>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct Attachment {
|
||||||
|
url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
#[allow(dead_code, non_camel_case_types)]
|
||||||
|
enum Visibility {
|
||||||
|
public,
|
||||||
|
unlisted,
|
||||||
|
private,
|
||||||
|
direct,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
struct PostForm {
|
||||||
|
status: String,
|
||||||
|
sensitive: bool,
|
||||||
|
visibility: Visibility,
|
||||||
|
media_ids: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn post_status(
|
||||||
|
client: &Client,
|
||||||
|
creds: &MastodonData,
|
||||||
|
config: &Config,
|
||||||
|
post: PostForm,
|
||||||
|
) -> DynResult<Post> {
|
||||||
|
Ok(client
|
||||||
|
.post(format!("{}/api/v1/statuses", &config.bot.instance))
|
||||||
|
.bearer_auth(&creds.token)
|
||||||
|
.header("Idempotency-Key", &post.status)
|
||||||
|
.json(&post)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json()
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct MediaAttachment {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upload_media(
|
||||||
|
client: &Client,
|
||||||
|
creds: &MastodonData,
|
||||||
|
config: &Config,
|
||||||
|
url: &String,
|
||||||
|
) -> DynResult<MediaAttachment> {
|
||||||
|
let image = reqwest::multipart::Form::new()
|
||||||
|
.text("description", url.to_string())
|
||||||
|
.file("file", &config.files.tempfile)
|
||||||
.await?;
|
.await?;
|
||||||
let mastodon = cli::authenticate(registration).await?;
|
|
||||||
|
|
||||||
// Save app data for using on the next run.
|
Ok(client
|
||||||
masto_toml::to_file(&mastodon.data, "mastodon-data.toml")?;
|
.post(format!("{}/api/v2/media", &config.bot.instance))
|
||||||
|
.bearer_auth(&creds.token)
|
||||||
Ok(mastodon)
|
.multipart(image)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json()
|
||||||
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|
||||||
|
async fn get_status(
|
||||||
|
client: &Client,
|
||||||
|
creds: &MastodonData,
|
||||||
|
config: &Config,
|
||||||
|
post_id: &String,
|
||||||
|
) -> DynResult<Post> {
|
||||||
|
Ok(client
|
||||||
|
.get(format!(
|
||||||
|
"{}/api/v1/statuses/{}",
|
||||||
|
&config.bot.instance, post_id
|
||||||
|
))
|
||||||
|
.bearer_auth(&creds.token)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json()
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
async fn delete_status(
|
||||||
|
client: &Client,
|
||||||
|
creds: &MastodonData,
|
||||||
|
config: &Config,
|
||||||
|
post_id: &String,
|
||||||
|
) -> DynResult<Post> {
|
||||||
|
Ok(client
|
||||||
|
.delete(format!(
|
||||||
|
"{}/api/v1/statuses/{}",
|
||||||
|
&config.bot.instance, post_id
|
||||||
|
))
|
||||||
|
.bearer_auth(&creds.token)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json()
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
use reqwest::StatusCode;
|
use reqwest::StatusCode;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
const TMPTESTDIR: &str = "/tmp/botimage";
|
const TMPTESTDIR: &str = "/tmp/botimage.png";
|
||||||
const TEST_URL: &str = "https://2.gravatar.com/avatar/be8eb8426d68e4beb50790647eda6f6b";
|
const TEST_URL: &str = "https://2.gravatar.com/avatar/be8eb8426d68e4beb50790647eda6f6b";
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
@ -349,45 +515,57 @@ mod tests {
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn post_should_post() {
|
async fn post_should_post() {
|
||||||
let client = reqwest::Client::builder().user_agent("bot").build().unwrap();
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("bot")
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
let config = get_config();
|
let config = get_config();
|
||||||
let account = get_account(&config).await;
|
let creds = get_mastodon_data(&client, &config).await;
|
||||||
let msg = "Test!".to_string();
|
let msg = "Test!".to_string();
|
||||||
|
|
||||||
let status = post(&account, &msg, Visibility::Direct).await.unwrap();
|
let status = post(&client, &creds, &config, &msg, Visibility::direct)
|
||||||
let response = client
|
.await
|
||||||
.get(format!(
|
.unwrap();
|
||||||
"{}/api/v1/statuses/{}",
|
let response = get_status(&client, &creds, &config, &status.id).await;
|
||||||
&config.bot.instance,
|
delete_status(&client, &creds, &config, &status.id)
|
||||||
&status.id.to_string()
|
|
||||||
))
|
|
||||||
.bearer_auth(&account.data.token)
|
|
||||||
.send()
|
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
account.delete_status(&status.id).await.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::OK)
|
response.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn post_image_works() {
|
async fn post_image_works() {
|
||||||
let client = reqwest::Client::builder().user_agent("bot").build().unwrap();
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("bot")
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
let config = get_config();
|
let config = get_config();
|
||||||
let account = get_account(&config).await;
|
let creds = get_mastodon_data(&client, &config).await;
|
||||||
|
|
||||||
let status = post_image(&account, &TEST_URL.to_string(), &config, Visibility::Direct)
|
let status = post_image(
|
||||||
|
&client,
|
||||||
|
&creds,
|
||||||
|
&config,
|
||||||
|
&TEST_URL.to_string(),
|
||||||
|
Visibility::direct,
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let response = account.get_status(&status.id).await.unwrap();
|
let response = get_status(&client, &creds, &config, &status.id)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
delete_status(&client, &creds, &config, &status.id)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
account.delete_status(&status.id).await.unwrap();
|
|
||||||
let attachment = &response.media_attachments[0];
|
let attachment = &response.media_attachments[0];
|
||||||
|
|
||||||
let response = client
|
let response = client
|
||||||
.get(attachment.url.clone().unwrap())
|
.get(&attachment.url)
|
||||||
.bearer_auth(&account.data.token)
|
.bearer_auth(&creds.token)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -402,7 +580,8 @@ mod tests {
|
||||||
let expected = insert_image(&config, IMAGE).await.unwrap();
|
let expected = insert_image(&config, IMAGE).await.unwrap();
|
||||||
|
|
||||||
set_url_as_posted(&config, &expected).await.unwrap();
|
set_url_as_posted(&config, &expected).await.unwrap();
|
||||||
let image: ImageWrap = reqwest::get(format!("{}/images/{}", config.backend.url, expected._id))
|
let image: ImageWrap =
|
||||||
|
reqwest::get(format!("{}/images/{}", config.backend.url, expected._id))
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.json()
|
.json()
|
||||||
|
@ -419,12 +598,12 @@ mod tests {
|
||||||
const IMAGE: &str = "https://picsum.photos/id/1";
|
const IMAGE: &str = "https://picsum.photos/id/1";
|
||||||
let expected = insert_image(&config, IMAGE).await.unwrap();
|
let expected = insert_image(&config, IMAGE).await.unwrap();
|
||||||
|
|
||||||
// Get test url
|
|
||||||
let image = get_next_url(&config).await.unwrap().unwrap();
|
let image = get_next_url(&config).await.unwrap().unwrap();
|
||||||
assert_eq!(image.url, IMAGE);
|
assert_eq!(image.url, IMAGE);
|
||||||
|
|
||||||
set_url_as_posted(&config, &expected).await.unwrap();
|
set_url_as_posted(&config, &expected).await.unwrap();
|
||||||
let image: ImageWrap = reqwest::get(format!("{}/images/{}", config.backend.url, expected._id))
|
let image: ImageWrap =
|
||||||
|
reqwest::get(format!("{}/images/{}", config.backend.url, expected._id))
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.json()
|
.json()
|
||||||
|
@ -433,13 +612,15 @@ mod tests {
|
||||||
let image = image.image;
|
let image = image.image;
|
||||||
assert_eq!(image.status, "consumed");
|
assert_eq!(image.status, "consumed");
|
||||||
|
|
||||||
// Test that now it does not get it
|
|
||||||
let image = get_next_url(&config).await.unwrap();
|
let image = get_next_url(&config).await.unwrap();
|
||||||
assert_eq!(image, None);
|
assert_eq!(image, None);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn insert_image(config: &Config, url: &str) -> DynResult<Image> {
|
async fn insert_image(config: &Config, url: &str) -> DynResult<Image> {
|
||||||
let client = reqwest::Client::builder().user_agent("bot").build().unwrap();
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent("bot")
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let auth = &Auth {
|
let auth = &Auth {
|
||||||
app: config.backend.app.to_string(),
|
app: config.backend.app.to_string(),
|
||||||
|
|
Loading…
Reference in New Issue