Tweaks
This commit is contained in:
parent
e34d343daf
commit
0c9e763e8c
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
|||||||
/target
|
/target
|
||||||
|
config.json
|
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -808,9 +808,11 @@ name = "miniflux-discord"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
|
"data-encoding",
|
||||||
"http-body-util",
|
"http-body-util",
|
||||||
"hyper 1.2.0",
|
"hyper 1.2.0",
|
||||||
"hyper-util",
|
"hyper-util",
|
||||||
|
"ring",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serenity",
|
"serenity",
|
||||||
|
@ -12,6 +12,7 @@ http-body-util = "0.1"
|
|||||||
hyper-util = { version = "0.1", features = ["tokio"] }
|
hyper-util = { version = "0.1", features = ["tokio"] }
|
||||||
serde = {version = "1.0", features = ["derive"]}
|
serde = {version = "1.0", features = ["derive"]}
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
# time = { version = "0.3.34", features = ["serde-well-known"] }
|
|
||||||
chrono = { version = "0.4.35", features = ["serde"] }
|
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;
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
struct Config {
|
pub struct Config {
|
||||||
discord_token: String,
|
pub host: IpAddr,
|
||||||
miniflux_base_url: String,
|
pub port: u16,
|
||||||
payload_max_size: u64,
|
pub discord_token: String,
|
||||||
whitelisted_user_ids: Vec<u64>,
|
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 http_body_util::{combinators::BoxBody, BodyExt, Full};
|
||||||
use hyper::{
|
use hyper::{
|
||||||
body::{self, Body, Bytes},
|
body::{self, Body, Bytes},
|
||||||
@ -9,6 +10,7 @@ use hyper::{
|
|||||||
};
|
};
|
||||||
use hyper_util::rt::TokioIo;
|
use hyper_util::rt::TokioIo;
|
||||||
use miniflux_requests::{Entry, Feed, MinifluxEvent, NewEntries};
|
use miniflux_requests::{Entry, Feed, MinifluxEvent, NewEntries};
|
||||||
|
use ring::hmac;
|
||||||
use serenity::{
|
use serenity::{
|
||||||
all::{
|
all::{
|
||||||
CacheHttp, Color, CreateButton, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter,
|
CacheHttp, Color, CreateButton, CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter,
|
||||||
@ -21,38 +23,31 @@ use tokio::net::TcpListener;
|
|||||||
mod config;
|
mod config;
|
||||||
mod miniflux_requests;
|
mod miniflux_requests;
|
||||||
|
|
||||||
const DISCORD_TOKEN: &'static str =
|
//FIXME!
|
||||||
"MTIxODMxMTU3NDM1MjAzOTk3Nw.G0ev0l.kZKr02qqgOiHNxO5bccVtYidnozufoKyAeXijQ";
|
const CONFIG_PATH: &'static str = "./config.json";
|
||||||
|
|
||||||
const MINIFLUX: &'static str = "";
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
// Create a new instance of the Client, logging in as a bot.
|
let config: Config = serde_json::from_slice(&fs::read(CONFIG_PATH).unwrap()).unwrap();
|
||||||
let client = Client::builder(&DISCORD_TOKEN, GatewayIntents::empty())
|
|
||||||
|
let client = Client::builder(&config.discord_token, GatewayIntents::empty())
|
||||||
.await
|
.await
|
||||||
.expect("Err creating client");
|
.expect("Err creating client");
|
||||||
|
|
||||||
let addr = SocketAddr::from(([0, 0, 0, 0], 8080));
|
let addr = SocketAddr::from((config.host, config.port));
|
||||||
|
|
||||||
// We create a TcpListener and bind it to 127.0.0.1:3000
|
|
||||||
let listener = TcpListener::bind(addr).await?;
|
let listener = TcpListener::bind(addr).await?;
|
||||||
|
|
||||||
// We start a loop to continuously accept incoming connections
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let (stream, _) = listener.accept().await?;
|
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 io = TokioIo::new(stream);
|
||||||
|
|
||||||
let cache = client.cache.clone();
|
let cache = client.cache.clone();
|
||||||
let http = client.http.clone();
|
let http = client.http.clone();
|
||||||
|
let config = config.clone();
|
||||||
|
|
||||||
// Spawn a tokio task to serve multiple connections concurrently
|
// Spawn a tokio task to serve multiple connections concurrently
|
||||||
tokio::task::spawn(async move {
|
tokio::task::spawn(async move {
|
||||||
// Finally, we bind the incoming connection to our `hello` service
|
|
||||||
if let Err(err) = http1::Builder::new()
|
if let Err(err) = http1::Builder::new()
|
||||||
// `service_fn` converts our function in a `Service`
|
// `service_fn` converts our function in a `Service`
|
||||||
.serve_connection(
|
.serve_connection(
|
||||||
@ -60,7 +55,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|||||||
service_fn(|req: Request<body::Incoming>| {
|
service_fn(|req: Request<body::Incoming>| {
|
||||||
let cache = cache.clone();
|
let cache = cache.clone();
|
||||||
let http = http.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
|
.await
|
||||||
@ -74,34 +70,31 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|||||||
async fn hello(
|
async fn hello(
|
||||||
req: Request<body::Incoming>,
|
req: Request<body::Incoming>,
|
||||||
ctx: impl CacheHttp + Copy,
|
ctx: impl CacheHttp + Copy,
|
||||||
|
config: &Config,
|
||||||
) -> Result<Response<BoxBody<hyper::body::Bytes, hyper::Error>>, Error> {
|
) -> Result<Response<BoxBody<hyper::body::Bytes, hyper::Error>>, Error> {
|
||||||
// todo check method
|
// todo check method
|
||||||
let _method = req.method();
|
let _method = req.method();
|
||||||
let headers = req.headers();
|
let headers = req.headers();
|
||||||
|
|
||||||
// todo fix unwrap
|
// todo fix unwrap
|
||||||
let userid = req
|
let userid = req.uri().path().split("/").nth(1).unwrap().parse::<u64>().unwrap();
|
||||||
.uri()
|
|
||||||
.path()
|
if !config.whitelisted_user_ids.contains(&userid) {
|
||||||
.split("/")
|
// Fixme!
|
||||||
.nth(1)
|
panic!("{} not allowed!", userid);
|
||||||
.unwrap()
|
}
|
||||||
.parse::<u64>()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let user = ctx.http().get_user(UserId::new(userid)).await.unwrap();
|
let user = ctx.http().get_user(UserId::new(userid)).await.unwrap();
|
||||||
|
|
||||||
// Todo remove expect
|
// Todo remove expect
|
||||||
// Todo make sure contents match signature
|
// Todo make sure contents match signature
|
||||||
let signature = headers
|
let signature_bytes =
|
||||||
.get("x-miniflux-signature")
|
headers.get("x-miniflux-signature").expect("expected signature").as_bytes();
|
||||||
.expect("expected signature");
|
let signature = data_encoding::HEXLOWER.decode(signature_bytes).unwrap();
|
||||||
let event_type = headers
|
let event_type = headers.get("x-miniflux-event-type").expect("expected event type").clone();
|
||||||
.get("x-miniflux-event-type")
|
|
||||||
.expect("expected event type");
|
|
||||||
|
|
||||||
let upper = req.body().size_hint().upper().unwrap_or(u64::MAX);
|
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"));
|
let mut resp = Response::new(full("Body too big"));
|
||||||
*resp.status_mut() = hyper::StatusCode::PAYLOAD_TOO_LARGE;
|
*resp.status_mut() = hyper::StatusCode::PAYLOAD_TOO_LARGE;
|
||||||
dbg!("Got message, too big!");
|
dbg!("Got message, too big!");
|
||||||
@ -110,33 +103,39 @@ async fn hello(
|
|||||||
|
|
||||||
let whole_body = req.collect().await?.to_bytes();
|
let whole_body = req.collect().await?.to_bytes();
|
||||||
let bytes = whole_body.iter().cloned().collect::<Vec<u8>>();
|
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![])))
|
Ok(Response::new(full(vec![])))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, hyper::Error> {
|
fn full<T: Into<Bytes>>(chunk: T) -> BoxBody<Bytes, hyper::Error> {
|
||||||
Full::new(chunk.into())
|
Full::new(chunk.into()).map_err(|never| match never {}).boxed()
|
||||||
.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 {
|
match event {
|
||||||
MinifluxEvent::New(NewEntries { feed, entries }) => {
|
MinifluxEvent::New(NewEntries { feed, entries }) => {
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
user.direct_message(ctx, message_from_entry(&entry, &feed))
|
user.direct_message(ctx, message_from_entry(&entry, &feed, config)).await.unwrap();
|
||||||
.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()
|
let content = MessageBuilder::new()
|
||||||
.push("New article from feed ")
|
.push("New article from feed ")
|
||||||
.push_named_link(&feed.title, &feed.site_url)
|
.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 author = CreateEmbedAuthor::new(&feed.title).url(&feed.site_url);
|
||||||
let footer = CreateEmbedFooter::new(format!("{} minutes", entry.reading_time.to_string()));
|
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()
|
let mut embed = CreateEmbed::new()
|
||||||
.title(&entry.title)
|
.title(&entry.title)
|
||||||
@ -165,24 +164,12 @@ fn message_from_entry(entry: &Entry, feed: &Feed) -> CreateMessage {
|
|||||||
embed = embed.field("Tags", entry.tags.join(","), true)
|
embed = embed.field("Tags", entry.tags.join(","), true)
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(enclosure) = entry
|
if let Some(enclosure) = entry.enclosures.iter().find(|e| e.mime_type.starts_with("image/")) {
|
||||||
.enclosures
|
|
||||||
.iter()
|
|
||||||
.find(|e| e.mime_type.starts_with("image/"))
|
|
||||||
{
|
|
||||||
embed = embed.image(&enclosure.url);
|
embed = embed.image(&enclosure.url);
|
||||||
}
|
}
|
||||||
|
|
||||||
let external_button = CreateButton::new_link(&entry.url)
|
let external_button = CreateButton::new_link(&entry.url).label("external").emoji('📤');
|
||||||
.label("external")
|
let minreq_button = CreateButton::new_link(minreq_url).label("minreq").emoji('📩');
|
||||||
.emoji('📤');
|
|
||||||
let minreq_button = CreateButton::new_link(minreq_url)
|
|
||||||
.label("minreq")
|
|
||||||
.emoji('📩');
|
|
||||||
|
|
||||||
CreateMessage::new()
|
CreateMessage::new().content(content).embed(embed).button(external_button).button(minreq_button)
|
||||||
.content(content)
|
|
||||||
.embed(embed)
|
|
||||||
.button(external_button)
|
|
||||||
.button(minreq_button)
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user