Init
This commit is contained in:
commit
2892a0d272
11 changed files with 2641 additions and 0 deletions
180
src/main.rs
Normal file
180
src/main.rs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use clap::Parser;
|
||||
use color_eyre::eyre::{eyre, Result, WrapErr};
|
||||
use directories::ProjectDirs;
|
||||
use figment::providers::Env;
|
||||
use figment::{
|
||||
providers::{Format, Toml},
|
||||
Figment,
|
||||
};
|
||||
use figment_file_provider_adapter::FileAdapter;
|
||||
use log::debug;
|
||||
use multimap::MultiMap;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use reddit_client::RedditClient;
|
||||
use crate::magnet::{extract_magnet_links, Magnet};
|
||||
|
||||
mod magnet;
|
||||
mod reddit_client;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SectionConfig {
|
||||
username: String,
|
||||
title_filter: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Config {
|
||||
#[serde(flatten)]
|
||||
sections: HashMap<String, SectionConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PostInfo {
|
||||
title: String,
|
||||
magnet_links: Vec<Magnet>,
|
||||
subreddit: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about = "Display recent posts from a Reddit user")]
|
||||
struct Args {
|
||||
/// Path to the configuration file
|
||||
#[arg(short, long)]
|
||||
config: Option<String>,
|
||||
}
|
||||
|
||||
/// Filters posts based on a title filter pattern
|
||||
fn filter_posts(title: &str, title_filter: Option<Regex>) -> bool {
|
||||
match title_filter {
|
||||
Some(pattern) => pattern.is_match(title),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the posts with their magnet links
|
||||
fn print_posts(posts: &[PostInfo], username: &str, title_filter: Option<Regex>) -> usize {
|
||||
println!("Magnet links from u/{}:", username);
|
||||
if let Some(pattern) = title_filter {
|
||||
println!("Filtering titles by pattern: {}", pattern);
|
||||
}
|
||||
println!("----------------------------");
|
||||
|
||||
let mut post_count = 0;
|
||||
|
||||
for post in posts {
|
||||
// Only display posts with magnet links
|
||||
if !post.magnet_links.is_empty() {
|
||||
post_count += 1;
|
||||
|
||||
println!(
|
||||
"{}. [r/{}] {} (Posted: {})",
|
||||
post_count,
|
||||
post.subreddit,
|
||||
post.title,
|
||||
post.timestamp.format("%Y-%m-%d %H:%M:%S")
|
||||
);
|
||||
|
||||
for (i, link) in post.magnet_links.iter().enumerate() {
|
||||
println!(" Link {}: {}", i + 1, link);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
}
|
||||
|
||||
if post_count == 0 {
|
||||
println!("No posts with magnet links found.");
|
||||
}
|
||||
|
||||
post_count
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
color_eyre::install()?;
|
||||
|
||||
let args = Args::parse();
|
||||
|
||||
let mut conf_extractor = Figment::new();
|
||||
let config_file_path: Option<PathBuf> = match args.config {
|
||||
Some(path) => Some(Path::new(&path).to_path_buf()),
|
||||
None => ProjectDirs::from("fr", "enoent", "reddit-magnet")
|
||||
.map(|p| p.config_dir().join("config.toml")),
|
||||
};
|
||||
match config_file_path {
|
||||
Some(path) => {
|
||||
if path.exists() {
|
||||
debug!("Reading configuration from {:?}", path);
|
||||
conf_extractor = conf_extractor.merge(FileAdapter::wrap(Toml::file_exact(path)));
|
||||
} else {
|
||||
debug!("Configuration file doesn't exist at {:?}", path);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
debug!("No configuration file specified, using default configuration");
|
||||
}
|
||||
}
|
||||
|
||||
let conf: Config = conf_extractor
|
||||
.merge(FileAdapter::wrap(Env::prefixed("REDDIT_MAGNET_")))
|
||||
.extract()
|
||||
.wrap_err_with(|| "Invalid configuration or insufficient command line arguments")?;
|
||||
|
||||
if conf.sections.is_empty() {
|
||||
return Err(eyre!("No configuration sections found. Please add at least one section to your configuration file.").into());
|
||||
}
|
||||
|
||||
let mut unique_usernames = HashSet::new();
|
||||
for (_, section_config) in &conf.sections {
|
||||
unique_usernames.insert(section_config.username.clone());
|
||||
}
|
||||
|
||||
let reddit_client = RedditClient::new();
|
||||
let mut user_posts = MultiMap::new();
|
||||
for username in unique_usernames {
|
||||
let submissions = reddit_client.fetch_user_submissions(&username).await?;
|
||||
user_posts.insert_many(username, submissions);
|
||||
}
|
||||
|
||||
for (section_name, section_config) in conf.sections {
|
||||
println!("\nProcessing section [{}]", section_name);
|
||||
|
||||
let username = section_config.username.clone();
|
||||
let title_filter = match section_config.title_filter {
|
||||
Some(filter) => Some(
|
||||
Regex::new(filter.as_str())
|
||||
.context(format!("Invalid regex pattern: {}", filter))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
|
||||
if let Some(submissions) = user_posts.get_vec(&username) {
|
||||
let mut filtered_posts = Vec::new();
|
||||
|
||||
for post in submissions.iter().filter(|s| filter_posts(&*s.title, title_filter.clone())) {
|
||||
let title = &post.title;
|
||||
let body = &post.body;
|
||||
let subreddit = &post.subreddit;
|
||||
|
||||
let magnet_links = extract_magnet_links(body);
|
||||
if !magnet_links.is_empty() {
|
||||
filtered_posts.push(PostInfo {
|
||||
title: title.to_string(),
|
||||
subreddit: subreddit.to_string(),
|
||||
magnet_links,
|
||||
timestamp: post.created,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
print_posts(&filtered_posts, &username, title_filter);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue