mirror of
https://codeberg.org/icewind/rss-webhook-trigger.git
synced 2026-11-30 04:00:49 +01:00
293 lines
8.9 KiB
Rust
293 lines
8.9 KiB
Rust
mod config;
|
|
mod error;
|
|
mod fetcher;
|
|
mod hub;
|
|
mod jwt;
|
|
|
|
use crate::config::{Config, FeedConfig, HeaderVal};
|
|
use crate::error::{FetchError, FetchFeedError, HubError, ParseFeedError, TriggerError};
|
|
use crate::fetcher::{CacheHeaders, FetchPlan, FetchResponse, next_fetch};
|
|
use crate::jwt::{generate_token, serve_well_known};
|
|
use main_error::MainResult;
|
|
use std::collections::HashMap;
|
|
use std::collections::hash_map::DefaultHasher;
|
|
use std::hash::{Hash, Hasher};
|
|
use std::str::FromStr;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::thread::{sleep, spawn};
|
|
use std::time::{Duration, Instant};
|
|
use tracing::{debug, error, info, instrument, warn};
|
|
use ureq::http::Response;
|
|
use ureq::http::header::{HeaderValue, USER_AGENT};
|
|
use ureq::{Agent, Body};
|
|
|
|
const FETCHER_USER_AGENT: &str = concat!(
|
|
env!("CARGO_PKG_NAME"),
|
|
"/",
|
|
env!("CARGO_PKG_VERSION"),
|
|
" (",
|
|
env!("CARGO_PKG_REPOSITORY"),
|
|
")"
|
|
);
|
|
|
|
static RUNNING: AtomicBool = AtomicBool::new(true);
|
|
|
|
fn main() -> MainResult {
|
|
tracing_subscriber::fmt::init();
|
|
let mut args = std::env::args();
|
|
let bin = args.next().unwrap();
|
|
|
|
let file = match args.next() {
|
|
Some(file) => file,
|
|
None => {
|
|
eprintln!("Usage {} <config file>", bin);
|
|
return Ok(());
|
|
}
|
|
};
|
|
|
|
let config = Config::from_file(&file)?;
|
|
|
|
if let Some(jwt_config) = config.jwt.clone()
|
|
&& let Some(listen) = jwt_config.listen.clone()
|
|
{
|
|
spawn(|| {
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
|
.enable_io()
|
|
.build()
|
|
.expect("Setup tokio");
|
|
if let Err(e) = rt.block_on(serve_well_known(jwt_config, listen)) {
|
|
eprintln!("{e:#}");
|
|
}
|
|
});
|
|
}
|
|
|
|
info!("Running rss trigger for {} feeds", config.feed.len());
|
|
|
|
ctrlc::set_handler(|| RUNNING.store(false, Ordering::SeqCst))?;
|
|
|
|
main_loop(config);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn main_loop(config: Config) {
|
|
let mut fetcher = FeedFetcher::new(config.interval());
|
|
|
|
while RUNNING.load(Ordering::SeqCst) {
|
|
for feed in config.feed.iter() {
|
|
match fetcher.check_feed_updated(&feed.feed) {
|
|
Ok(true) => {
|
|
if let Err(e) = trigger(&fetcher.client, feed, &config) {
|
|
error!("{:#}", e);
|
|
}
|
|
}
|
|
Err(e) => error!(error = ?e, feed = feed.feed, "failed to check feed"),
|
|
Ok(false) => {}
|
|
}
|
|
}
|
|
|
|
interruptible_sleep(config.interval());
|
|
}
|
|
}
|
|
|
|
fn interruptible_sleep(duration: Duration) {
|
|
let target = Instant::now() + duration;
|
|
while Instant::now() < target && RUNNING.load(Ordering::SeqCst) {
|
|
sleep(Duration::from_millis(100));
|
|
}
|
|
}
|
|
|
|
#[instrument(skip_all, fields(feed = feed.feed))]
|
|
fn trigger(client: &Agent, feed: &FeedConfig, config: &Config) -> Result<(), TriggerError> {
|
|
info!("Triggering hook");
|
|
let mut req = client
|
|
.post(&feed.hook)
|
|
.header("user-agent", "rss-webhook-trigger");
|
|
for (key, value) in &feed.headers {
|
|
let value = match value {
|
|
HeaderVal::String(s) => s.clone(),
|
|
HeaderVal::Jwt { aud } => format!("Bearer {}", generate_token(config, aud)?),
|
|
};
|
|
req = req.header(key, value);
|
|
}
|
|
|
|
debug!(request = ?req, "sending trigger request");
|
|
if feed.body.is_null() {
|
|
req.send_json(&feed.body)?;
|
|
} else {
|
|
req.send_empty()?;
|
|
};
|
|
Ok(())
|
|
}
|
|
|
|
pub struct FeedFetcher {
|
|
client: Agent,
|
|
base_interval: Duration,
|
|
cache: HashMap<String, u64>,
|
|
fetch_plans: HashMap<String, FetchPlan>,
|
|
}
|
|
|
|
impl FeedFetcher {
|
|
pub fn new(interval: Duration) -> Self {
|
|
FeedFetcher {
|
|
client: Agent::new_with_defaults(),
|
|
base_interval: interval,
|
|
cache: HashMap::default(),
|
|
fetch_plans: HashMap::default(),
|
|
}
|
|
}
|
|
|
|
pub fn should_update(&self, feed: &str) -> bool {
|
|
match self.fetch_plans.get(feed) {
|
|
Some(plan) => plan.is_elapsed(),
|
|
None => true,
|
|
}
|
|
}
|
|
|
|
#[instrument(skip(self))]
|
|
pub fn check_feed_updated(&mut self, feed: &str) -> Result<bool, FetchError> {
|
|
if !self.should_update(feed) {
|
|
warn!("skipping feed util rate limited expires");
|
|
return Ok(false);
|
|
}
|
|
let plan = self.fetch_plans.remove(feed).unwrap_or_default();
|
|
|
|
let fetch_result = self.get_feed_key(feed, &plan.headers);
|
|
let (result, new_plan) = fetch_result.into_result();
|
|
let is_retry = new_plan.is_retry();
|
|
self.fetch_plans
|
|
.insert(feed.into(), next_fetch(self.base_interval, Some(new_plan)));
|
|
let new_key = result?;
|
|
|
|
Ok(match (self.cache.get_mut(feed), new_key) {
|
|
(Some(cached), Some(new_key)) => {
|
|
debug!(cached, new_key, "checked existing feed");
|
|
if new_key != *cached {
|
|
*cached = new_key;
|
|
info!("feed updated");
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
(None, Some(new_key)) => {
|
|
debug!(feed, "new feed");
|
|
self.cache.insert(feed.into(), new_key);
|
|
|
|
// don't trigger the actions on start
|
|
false
|
|
}
|
|
(_, None) if is_retry => {
|
|
warn!("rate limited by server");
|
|
false
|
|
}
|
|
(_, None) => {
|
|
debug!("not modified");
|
|
false
|
|
}
|
|
})
|
|
}
|
|
|
|
#[instrument(skip(self))]
|
|
fn get_feed_key(
|
|
&self,
|
|
feed: &str,
|
|
cache_headers: &CacheHeaders,
|
|
) -> FetchResponse<u64, FetchError> {
|
|
if let Some(hub) = feed.strip_prefix("docker-hub://") {
|
|
if let Some((user, repo)) = hub.split_once('/') {
|
|
hub::tags(&self.client, user, repo, cache_headers)
|
|
.map(|tags| {
|
|
let mut hasher = DefaultHasher::new();
|
|
for tag in tags {
|
|
tag.id.hash(&mut hasher);
|
|
tag.last_updated.hash(&mut hasher);
|
|
}
|
|
hasher.finish()
|
|
})
|
|
.map_err(FetchError::Hub)
|
|
} else {
|
|
FetchResponse::Error {
|
|
error: HubError::InvalidFormat.into(),
|
|
headers: CacheHeaders::default(),
|
|
}
|
|
}
|
|
} else {
|
|
self.get_rss_feed_key(feed, cache_headers)
|
|
.map_err(FetchError::Feed)
|
|
}
|
|
}
|
|
|
|
#[instrument(skip(self))]
|
|
fn get_rss_feed_key(
|
|
&self,
|
|
feed: &str,
|
|
cache_headers: &CacheHeaders,
|
|
) -> FetchResponse<u64, FetchFeedError> {
|
|
let mut req = self
|
|
.client
|
|
.get(feed)
|
|
.header(USER_AGENT, HeaderValue::from_static(FETCHER_USER_AGENT));
|
|
cache_headers.set_headers(req.headers_mut().unwrap());
|
|
|
|
let response = req.call();
|
|
|
|
let plan_result = FetchResponse::from_result(response);
|
|
plan_result
|
|
.map_err(FetchFeedError::Network)
|
|
.check_status_code(FetchFeedError::ClientError, FetchFeedError::ServerError)
|
|
.map(parse_rss_response)
|
|
.flatten()
|
|
}
|
|
}
|
|
|
|
/// Taken from the `syndication`, which hasn't seen a release in 6 years, has outdated dependencies, but it also *just* this one `enum`.
|
|
#[derive(Clone)]
|
|
#[allow(clippy::large_enum_variant)]
|
|
pub enum Feed {
|
|
Atom(atom_syndication::Feed),
|
|
RSS(rss::Channel),
|
|
}
|
|
|
|
impl FromStr for Feed {
|
|
type Err = &'static str;
|
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
match atom_syndication::Feed::from_str(s) {
|
|
Ok(feed) => Ok(Feed::Atom(feed)),
|
|
_ => match rss::Channel::from_str(s) {
|
|
Ok(feed) => Ok(Feed::RSS(feed)),
|
|
_ => Err("Could not parse XML as Atom or RSS from input"),
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
fn parse_rss_response(response: Response<Body>) -> Result<u64, FetchFeedError> {
|
|
let content = response.into_body().read_to_string()?;
|
|
let channel = Feed::from_str(&content).map_err(ParseFeedError::Parse)?;
|
|
|
|
let mut hasher = DefaultHasher::new();
|
|
|
|
match channel {
|
|
Feed::RSS(channel) => {
|
|
let item = channel.items.first().ok_or(ParseFeedError::Empty)?;
|
|
|
|
if let Some(guid) = item.guid() {
|
|
guid.value.hash(&mut hasher);
|
|
} else if let Some(date) = item.pub_date() {
|
|
date.hash(&mut hasher);
|
|
} else if let Some(link) = item.link() {
|
|
link.hash(&mut hasher);
|
|
} else {
|
|
return Err(ParseFeedError::MissingKey.into());
|
|
}
|
|
}
|
|
Feed::Atom(channel) => {
|
|
let item = channel.entries().first().ok_or(ParseFeedError::Empty)?;
|
|
item.id().hash(&mut hasher);
|
|
}
|
|
}
|
|
|
|
Ok(hasher.finish())
|
|
}
|