176 lines
5.9 KiB
Rust
176 lines
5.9 KiB
Rust
use std::{fs, net::SocketAddr};
|
|
|
|
use config::Config;
|
|
use http_body_util::{combinators::BoxBody, BodyExt, Full};
|
|
use hyper::{
|
|
body::{self, Body, Bytes},
|
|
server::conn::http1,
|
|
service::service_fn,
|
|
Error, Request, Response,
|
|
};
|
|
use hyper_util::rt::TokioIo;
|
|
use miniflux_requests::{Entry, Feed, MinifluxEvent, NewEntries};
|
|
use ring::hmac;
|
|
use serenity::{
|
|
all::{
|
|
CacheHttp, Color, CreateButton, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter,
|
|
CreateMessage, EmbedMessageBuilding, GatewayIntents, MessageBuilder, User, UserId,
|
|
},
|
|
Client,
|
|
};
|
|
use tokio::net::TcpListener;
|
|
|
|
mod config;
|
|
mod miniflux_requests;
|
|
|
|
//FIXME!
|
|
const CONFIG_PATH: &'static str = "./config.json";
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|
let config: Config = serde_json::from_slice(&fs::read(CONFIG_PATH).unwrap()).unwrap();
|
|
|
|
let client = Client::builder(&config.discord_token, GatewayIntents::empty())
|
|
.await
|
|
.expect("Err creating client");
|
|
|
|
let addr = SocketAddr::from((config.host, config.port));
|
|
let listener = TcpListener::bind(addr).await?;
|
|
|
|
loop {
|
|
let (stream, _) = listener.accept().await?;
|
|
|
|
let io = TokioIo::new(stream);
|
|
|
|
let cache = client.cache.clone();
|
|
let http = client.http.clone();
|
|
let config = config.clone();
|
|
|
|
// Spawn a tokio task to serve multiple connections concurrently
|
|
tokio::task::spawn(async move {
|
|
if let Err(err) = http1::Builder::new()
|
|
// `service_fn` converts our function in a `Service`
|
|
.serve_connection(
|
|
io,
|
|
service_fn(|req: Request<body::Incoming>| {
|
|
let cache = cache.clone();
|
|
let http = http.clone();
|
|
let config = config.clone();
|
|
async move { hello(req, (&cache, http.as_ref()), &config).await }
|
|
}),
|
|
)
|
|
.await
|
|
{
|
|
println!("Error serving connection: {:?}", err);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
async fn hello(
|
|
req: Request<body::Incoming>,
|
|
ctx: impl CacheHttp + Copy,
|
|
config: &Config,
|
|
) -> Result<Response<BoxBody<hyper::body::Bytes, hyper::Error>>, Error> {
|
|
// todo check method
|
|
let _method = req.method();
|
|
let headers = req.headers();
|
|
|
|
// todo fix unwrap
|
|
let userid = req.uri().path().split("/").nth(1).unwrap().parse::<u64>().unwrap();
|
|
|
|
if !config.whitelisted_user_ids.contains(&userid) {
|
|
// Fixme!
|
|
panic!("{} not allowed!", userid);
|
|
}
|
|
|
|
let user = ctx.http().get_user(UserId::new(userid)).await.unwrap();
|
|
|
|
// Todo remove expect
|
|
// Todo make sure contents match signature
|
|
let signature_bytes =
|
|
headers.get("x-miniflux-signature").expect("expected signature").as_bytes();
|
|
let signature = data_encoding::HEXLOWER.decode(signature_bytes).unwrap();
|
|
let event_type = headers.get("x-miniflux-event-type").expect("expected event type").clone();
|
|
|
|
let upper = req.body().size_hint().upper().unwrap_or(u64::MAX);
|
|
if upper > config.payload_max_size {
|
|
let mut resp = Response::new(full("Body too big"));
|
|
*resp.status_mut() = hyper::StatusCode::PAYLOAD_TOO_LARGE;
|
|
dbg!("Got message, too big!");
|
|
return Ok(resp);
|
|
}
|
|
|
|
let whole_body = req.collect().await?.to_bytes();
|
|
let bytes = whole_body.iter().cloned().collect::<Vec<u8>>();
|
|
|
|
let key = hmac::Key::new(hmac::HMAC_SHA256, &config.miniflux_webhook_secret.as_bytes());
|
|
|
|
// TODO! Remove unwrap!
|
|
hmac::verify(&key, &bytes, &signature).unwrap();
|
|
|
|
let event: MinifluxEvent = serde_json::from_slice(&bytes).unwrap();
|
|
match event {
|
|
MinifluxEvent::New(_) => assert!(event_type == "new_entries"),
|
|
MinifluxEvent::Save(_) => assert!(event_type == "save_entry"),
|
|
}
|
|
|
|
send(user, ctx, event, config).await;
|
|
|
|
Ok(Response::new(full(vec![])))
|
|
}
|
|
|
|
fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, hyper::Error> {
|
|
Full::new(chunk.into()).map_err(|never| match never {}).boxed()
|
|
}
|
|
|
|
async fn send(user: User, ctx: impl CacheHttp + Copy, event: MinifluxEvent, config: &Config) {
|
|
match event {
|
|
MinifluxEvent::New(NewEntries { feed, entries }) => {
|
|
for entry in entries {
|
|
user.direct_message(ctx, message_from_entry(&entry, &feed, config)).await.unwrap();
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn message_from_entry(entry: &Entry, feed: &Feed, config: &Config) -> CreateMessage {
|
|
let content = MessageBuilder::new()
|
|
.push("New article from feed ")
|
|
.push_named_link(&feed.title, &feed.site_url)
|
|
.push(" published!")
|
|
.build();
|
|
|
|
let author = CreateEmbedAuthor::new(&feed.title).url(&feed.site_url);
|
|
let footer = CreateEmbedFooter::new(format!("{} minutes", entry.reading_time.to_string()));
|
|
|
|
let minreq_url = format!("{}/feed/{}/entry/{}", config.miniflux_base_url, feed.id, entry.id);
|
|
|
|
let mut embed = CreateEmbed::new()
|
|
.title(&entry.title)
|
|
.url(&entry.url)
|
|
.footer(footer)
|
|
.timestamp(entry.published_at)
|
|
.author(author)
|
|
.color(Color::from_rgb(
|
|
(feed.id % 256) as u8,
|
|
((feed.id * feed.id) % 256) as u8,
|
|
((feed.id * feed.id * feed.id) % 256) as u8,
|
|
))
|
|
.description(&entry.content.chars().take(200).collect::<String>());
|
|
|
|
if entry.tags.len() > 0 {
|
|
embed = embed.field("Tags", entry.tags.join(","), true)
|
|
}
|
|
|
|
if let Some(enclosure) = entry.enclosures.iter().find(|e| e.mime_type.starts_with("image/")) {
|
|
embed = embed.image(&enclosure.url);
|
|
}
|
|
|
|
let external_button = CreateButton::new_link(&entry.url).label("external").emoji('📤');
|
|
let minreq_button = CreateButton::new_link(minreq_url).label("minreq").emoji('📩');
|
|
|
|
CreateMessage::new().content(content).embed(embed).button(external_button).button(minreq_button)
|
|
}
|