added new pad generator

This commit is contained in:
murmeldin 2024-07-23 17:44:07 +02:00 committed by murmeldin
parent e2bd4780a2
commit 7e91eae81b
4 changed files with 128 additions and 19 deletions

View file

@ -17,6 +17,7 @@ lettre = "0.11.7"
rand = "0.9.0-alpha.1" rand = "0.9.0-alpha.1"
rusqlite = "0.31.0" rusqlite = "0.31.0"
uuid = { version = "1.10.0", features = ["v4"] } uuid = { version = "1.10.0", features = ["v4"] }
log = "0.4.22"
#mail-core = "0.6.2" #mail-core = "0.6.2"
#mail-headers = "0.6.6" #mail-headers = "0.6.6"
#mail-internals = "0.2.3" #mail-internals = "0.2.3"

59
src/create_new_pads.rs Normal file
View file

@ -0,0 +1,59 @@
use reqwest::Client;
use std::error::Error;
pub async fn create_pad(client: &Client, hedgedoc_url: &str) -> Result<String, Box<dyn Error>> {
let res = client.get(format!("{}/new", hedgedoc_url)).send().await?;
if res.status().is_success() {
let pad_url = res.url().to_string();
Ok(pad_url)
} else {
Err(format!("Failed to create pad: {} - {}", res.status(), res.text().await?).into())
}
}
pub async fn import_note(client: &Client, content: String, note_id: Option<&str>, hedgedoc_url: &str) -> Result<String, Box<dyn Error>> {
let post_url = match note_id {
Some(id) => format!("{}/new/{}", hedgedoc_url, id),
None => format!("{}/new", hedgedoc_url),
};
let content_parsed: String = content.clone().to_string();
println!("Content Parsed:");
println!("{}", content_parsed);
let res = client.post(&post_url)
.header("Content-Type", "text/markdown")
.body(content_parsed)
.send()
.await?;
if res.status().is_success() {
let final_url = res.url().to_string();
Ok(final_url)
} else {
Err(format!("Failed to import note: {} - {}", res.status(), res.text().await?).into())
}
}
/*
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let client = Client::new();
match create_pad(&client).await {
Ok(pad_url) => {
println!("Pad created successfully at URL: {}", pad_url);
let pad_id = pad_url.trim_start_matches(&format!("{}/", HEDGEDOC_URL));
match import_note(&client, TEMPLATE_CONTENT, Some(pad_id)).await {
Ok(_) => println!("Pad updated successfully with template content."),
Err(e) => println!("Failed to update pad: {}", e),
}
}
Err(e) => println!("Failed to create pad: {}", e),
}
Ok(())
}
*/

View file

@ -19,25 +19,34 @@ Pad-ins-Wiki-und-versenden-Skript
Neue Wiki-Seite erstellen und dort das umgewandelte Pad hochladen Neue Wiki-Seite erstellen und dort das umgewandelte Pad hochladen
*/ */
// Import other .rs files as modules
mod key_value; mod key_value;
use key_value::KeyValueStore as KV; use key_value::KeyValueStore as KV;
mod create_new_pads;
pub mod variables_and_settings;
use chrono::{Datelike, Local, NaiveDate, Weekday}; use chrono::{Datelike, Local, NaiveDate, Weekday};
use regex::{Regex}; use regex::{Regex};
use uuid::Uuid; use uuid::Uuid;
use std::process::Command; use reqwest::Client;
use headers::ContentType; use std::error::Error;
use std::future::Future;
// use std::process::Command;
// use headers::ContentType;
// MAIL START // MAIL START
use lettre::{Message, SmtpTransport, Transport}; use lettre::{Message, SmtpTransport, Transport};
use lettre::message::{header, SinglePart}; use lettre::message::{header, SinglePart};
use lettre::message::header::MessageId; use lettre::message::header::MessageId;
use lettre::transport::smtp::authentication::Credentials; use lettre::transport::smtp::authentication::Credentials;
use log::error;
// MAIL END // MAIL END
use rand::{Rng, thread_rng}; const HEDGEDOC_SERVER_URL: &str = variables_and_settings::HEDGEDOC_SERVER_URL;
use rand::distributions::Alphanumeric; const PLENUM_TEMPLATE_URL: &str = variables_and_settings::PLENUM_TEMPLATE_URL;
const FALLBACK_TEMPLATE: &str = variables_and_settings::FALLBACK_TEMPLATE;
fn kv_defaults (kv: KV) { fn kv_defaults (kv: KV) {
kv.default("template-url", "https://md.berlin.ccc.de/plenum-template"); kv.default("template-url", "https://md.berlin.ccc.de/plenum-template");
@ -70,15 +79,15 @@ async fn main() {
// Nächste Plena nachschauen: // Nächste Plena nachschauen:
let nächster_plenumtermin = if all_tuesdays[1].unwrap() >= today_simple.pred_opt().unwrap() { // Für das Pad rumschicken am nächsten Tag wird das Datum einen Tag nach Hinten gesetzt, let nächster_plenumtermin: String = if all_tuesdays[1].unwrap() >= today_simple.pred_opt().unwrap() { // Für das Pad rumschicken am nächsten Tag wird das Datum einen Tag nach Hinten gesetzt,
&zweiter_dienstag zweiter_dienstag.clone()
} else { } else {
&vierter_dienstag vierter_dienstag.clone()
}; };
let übernächster_plenumtermin = if all_tuesdays[1].unwrap() >= today_simple.pred_opt().unwrap() { // hier das Gleiche. let übernächster_plenumtermin = if all_tuesdays[1].unwrap() >= today_simple.pred_opt().unwrap() { // hier das Gleiche.
&vierter_dienstag vierter_dienstag.clone()
} else { } else {
&zweiter_dienstag_nächster_monat zweiter_dienstag_nächster_monat.clone()
}; };
// Der Code muss nur für vor dem 2. und vor dem 4. Dienstag gebaut werden, weil im nächsten Monat der Code frühestens 7 Tage vor dem Plenum wieder passt. // Der Code muss nur für vor dem 2. und vor dem 4. Dienstag gebaut werden, weil im nächsten Monat der Code frühestens 7 Tage vor dem Plenum wieder passt.
@ -123,8 +132,7 @@ async fn main() {
println!("message id: {}", message_id) println!("message id: {}", message_id)
} }
// END ANKÜNDIGUNGSSCRIPT // END ANKÜNDIGUNGSSCRIPT
let datum = String::from("15.10.24"); generate_new_pad_for_following_date(nächster_plenumtermin, übernächster_plenumtermin).await.expect("Fehler! Plenumspad konnte nicht generiert werden!");
generate_new_pad_for_following_date(datum);
} }
@ -217,12 +225,36 @@ fn mail_versenden(inhalt: String, betreff: String) -> std::result::Result<String
Ok(message_id) Ok(message_id)
} }
fn generate_new_pad_for_following_date(datum: String) { async fn generate_new_pad_for_following_date(nächster_plenumtermin: String, übernächster_plenumtermin: String) -> Result<(), Box<dyn Error>> {
let rand_string: String = thread_rng() let client = Client::new();
.sample_iter(&Alphanumeric)
.take(22)
.map(char::from)
.collect();
println!("{}", rand_string) match create_new_pads::create_pad(&client, HEDGEDOC_SERVER_URL).await {
Ok(pad_url) => {
println!("Pad created successfully at URL: {}", pad_url);
// Get the most recent plenum template and replace the placeholders:
let template_from_pad = download_and_return_pad(PLENUM_TEMPLATE_URL.to_string()).await; // Download Pad
let template_content: String = template_from_pad.unwrap_or_else(|error| FALLBACK_TEMPLATE.to_string()); // If Download wasn't successful, use offline Template
let template_modified: String = replace_placeholders(&template_content, nächster_plenumtermin, übernächster_plenumtermin).unwrap_or_else(|error |template_content); // Try regex, if not successful use without regex
let pad_id: &str = pad_url.trim_start_matches(&format!("{}/", HEDGEDOC_SERVER_URL));
match create_new_pads::import_note(&client, template_modified, Some(pad_id), HEDGEDOC_SERVER_URL).await {
Ok(_) => println!("Pad updated successfully with template content."),
Err(e) => println!("Failed to update pad: {}", e),
}
}
Err(e) => println!("Failed to create pad: {}", e),
}
Ok(())
}
fn replace_placeholders(template: &str, nächster_plenumtermin: String, übernächster_plenumtermin: String) -> Result<String, Box<dyn Error>> {
let re_datum = Regex::new(r"\{\{Datum\}\}")?;
let re_naechstes_plenum = Regex::new(r"\{\{naechstes-plenum\}\}")?;
let result = re_datum.replace_all(template, nächster_plenumtermin);
let result = re_naechstes_plenum.replace_all(&result, übernächster_plenumtermin);
Ok(result.to_string())
} }

View file

@ -0,0 +1,17 @@
pub const FALLBACK_TEMPLATE: &str = r#"
# Welcome to HedgeDoc
This is a template pad.
## Section 1
- Item 1
- Item 2
## Section 2
Add more content here...
"#;
pub const PLENUM_TEMPLATE_URL: &str = "https://md.berlin.ccc.de/plenum-template/download";
pub const HEDGEDOC_SERVER_URL: &str = "https://md.berlin.ccc.de";