caveman/src/worker.rs

49 lines
1.6 KiB
Rust
Raw Normal View History

2022-11-02 21:12:16 +01:00
use std::collections::HashSet;
2022-11-02 22:06:43 +01:00
use std::time::Duration;
2022-11-02 21:12:16 +01:00
use crate::feed;
#[derive(Debug)]
pub enum Message {
2022-11-02 22:06:43 +01:00
Fetched { host: String, next_interval: Duration },
2022-11-02 21:12:16 +01:00
Error { host: String },
IntroduceHosts { hosts: Vec<String> },
Posts { posts: Vec<feed::Post> },
}
pub fn fetch_and_process(
tx: tokio::sync::mpsc::UnboundedSender<Message>,
client: reqwest::Client,
host: String,
) {
let url = format!("https://{}/api/v1/timelines/public", host);
tokio::spawn(async move {
match feed::Feed::fetch(&client, &url).await {
Ok(feed) => {
// Analyze
let mut posts = Vec::with_capacity(feed.posts.len());
let mut hosts = HashSet::new();
for post in feed.posts.into_iter() {
if let Some(author_host) = post.account.host() {
2022-11-02 21:49:37 +01:00
if author_host == host && post.url_host().as_ref() == Some(&host) {
2022-11-02 21:12:16 +01:00
posts.push(post);
}
hosts.insert(author_host);
}
}
let hosts = hosts.into_iter().collect();
tx.send(Message::IntroduceHosts { hosts }).unwrap();
tx.send(Message::Posts { posts }).unwrap();
2022-11-02 22:06:43 +01:00
tx.send(Message::Fetched {
host: host.clone(),
next_interval: Duration::from_secs(10),
}).unwrap();
2022-11-02 21:12:16 +01:00
}
Err(e) => {
println!("Failed fetching {}: {}", host, e);
tx.send(Message::Error { host }).unwrap();
}
}
});
}