Tweaks
This commit is contained in:
parent
e34d343daf
commit
0c9e763e8c
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
||||
/target
|
||||
config.json
|
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -808,9 +808,11 @@ name = "miniflux-discord"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"data-encoding",
|
||||
"http-body-util",
|
||||
"hyper 1.2.0",
|
||||
"hyper-util",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serenity",
|
||||
|
@ -12,6 +12,7 @@ http-body-util = "0.1"
|
||||
hyper-util = { version = "0.1", features = ["tokio"] }
|
||||
serde = {version = "1.0", features = ["derive"]}
|
||||
serde_json = "1.0"
|
||||
# time = { version = "0.3.34", features = ["serde-well-known"] }
|
||||
chrono = { version = "0.4.35", features = ["serde"] }
|
||||
serenity = "0.12"
|
||||
serenity = { version = "0.12" }
|
||||
ring = { version = "0.17.8" }
|
||||
data-encoding = "2.5"
|
5
rustfmt.toml
Normal file
5
rustfmt.toml
Normal file
@ -0,0 +1,5 @@
|
||||
max_width = 100
|
||||
imports_granularity = "Module"
|
||||
group_imports = "StdExternalCrate"
|
||||
version = "Two"
|
||||
use_small_heuristics = "Max"
|
@ -1,9 +1,14 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct Config {
|
||||
discord_token: String,
|
||||
miniflux_base_url: String,
|
||||
payload_max_size: u64,
|
||||
whitelisted_user_ids: Vec<u64>,
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub host: IpAddr,
|
||||
pub port: u16,
|
||||
pub discord_token: String,
|
||||
pub miniflux_base_url: String,
|
||||
pub miniflux_webhook_secret: String,
|
||||
pub payload_max_size: u64,
|
||||
pub whitelisted_user_ids: Vec<u64>,
|
||||
}
|
||||
|
103
src/main.rs
103
src/main.rs
@ -1,5 +1,6 @@
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
use std::{fs, net::SocketAddr};
|
||||
|
||||
use config::Config;
|
||||
use http_body_util::{combinators::BoxBody, BodyExt, Full};
|
||||
use hyper::{
|
||||
body::{self, Body, Bytes},
|
||||
@ -9,6 +10,7 @@ use hyper::{
|
||||
};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use miniflux_requests::{Entry, Feed, MinifluxEvent, NewEntries};
|
||||
use ring::hmac;
|
||||
use serenity::{
|
||||
all::{
|
||||
CacheHttp, Color, CreateButton, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter,
|
||||
@ -21,38 +23,31 @@ use tokio::net::TcpListener;
|
||||
mod config;
|
||||
mod miniflux_requests;
|
||||
|
||||
const DISCORD_TOKEN: &'static str =
|
||||
"MTIxODMxMTU3NDM1MjAzOTk3Nw.G0ev0l.kZKr02qqgOiHNxO5bccVtYidnozufoKyAeXijQ";
|
||||
|
||||
const MINIFLUX: &'static str = "";
|
||||
//FIXME!
|
||||
const CONFIG_PATH: &'static str = "./config.json";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
// Create a new instance of the Client, logging in as a bot.
|
||||
let client = Client::builder(&DISCORD_TOKEN, GatewayIntents::empty())
|
||||
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(([0, 0, 0, 0], 8080));
|
||||
|
||||
// We create a TcpListener and bind it to 127.0.0.1:3000
|
||||
let addr = SocketAddr::from((config.host, config.port));
|
||||
let listener = TcpListener::bind(addr).await?;
|
||||
|
||||
// We start a loop to continuously accept incoming connections
|
||||
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
|
||||
// Use an adapter to access something implementing `tokio::io` traits as if they implement
|
||||
// `hyper::rt` IO traits.
|
||||
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 {
|
||||
// Finally, we bind the incoming connection to our `hello` service
|
||||
if let Err(err) = http1::Builder::new()
|
||||
// `service_fn` converts our function in a `Service`
|
||||
.serve_connection(
|
||||
@ -60,7 +55,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
service_fn(|req: Request<body::Incoming>| {
|
||||
let cache = cache.clone();
|
||||
let http = http.clone();
|
||||
async move { hello(req, (&cache, http.as_ref())).await }
|
||||
let config = config.clone();
|
||||
async move { hello(req, (&cache, http.as_ref()), &config).await }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
@ -74,34 +70,31 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
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();
|
||||
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 = headers
|
||||
.get("x-miniflux-signature")
|
||||
.expect("expected signature");
|
||||
let event_type = headers
|
||||
.get("x-miniflux-event-type")
|
||||
.expect("expected event type");
|
||||
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 > 1024 * 1024 * 10 {
|
||||
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!");
|
||||
@ -110,33 +103,39 @@ async fn hello(
|
||||
|
||||
let whole_body = req.collect().await?.to_bytes();
|
||||
let bytes = whole_body.iter().cloned().collect::<Vec<u8>>();
|
||||
let event: MinifluxEvent = serde_json::from_slice(&bytes).unwrap();
|
||||
|
||||
send(user, ctx, event).await;
|
||||
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()
|
||||
Full::new(chunk.into()).map_err(|never| match never {}).boxed()
|
||||
}
|
||||
|
||||
async fn send(user: User, ctx: impl CacheHttp + Copy, event: MinifluxEvent) {
|
||||
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))
|
||||
.await
|
||||
.unwrap();
|
||||
user.direct_message(ctx, message_from_entry(&entry, &feed, config)).await.unwrap();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn message_from_entry(entry: &Entry, feed: &Feed) -> CreateMessage {
|
||||
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)
|
||||
@ -146,7 +145,7 @@ fn message_from_entry(entry: &Entry, feed: &Feed) -> CreateMessage {
|
||||
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/{}", MINIFLUX, feed.id, entry.id);
|
||||
let minreq_url = format!("{}/feed/{}/entry/{}", config.miniflux_base_url, feed.id, entry.id);
|
||||
|
||||
let mut embed = CreateEmbed::new()
|
||||
.title(&entry.title)
|
||||
@ -165,24 +164,12 @@ fn message_from_entry(entry: &Entry, feed: &Feed) -> CreateMessage {
|
||||
embed = embed.field("Tags", entry.tags.join(","), true)
|
||||
}
|
||||
|
||||
if let Some(enclosure) = entry
|
||||
.enclosures
|
||||
.iter()
|
||||
.find(|e| e.mime_type.starts_with("image/"))
|
||||
{
|
||||
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('📩');
|
||||
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)
|
||||
CreateMessage::new().content(content).embed(embed).button(external_button).button(minreq_button)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user