// CRATES use actix_web::{get, web, HttpResponse, Result}; use askama::Template; use chrono::{TimeZone, Utc}; #[path = "utils.rs"] mod utils; pub use utils::{val, Flair, Params, Post, Subreddit, request}; // STRUCTS #[derive(Template)] #[template(path = "subreddit.html", escape = "none")] struct SubredditTemplate { sub: Subreddit, posts: Vec, sort: String, } async fn render(sub_name: String, sort: String) -> Result { let mut sub: Subreddit = subreddit(&sub_name).await?; let posts: Vec = posts(sub_name, &sort).await?; sub.icon = if sub.icon != "" { format!(r#""#, sub.icon) } else { String::new() }; let s = SubredditTemplate { sub: sub, posts: posts, sort: sort }.render().unwrap(); Ok(HttpResponse::Ok().content_type("text/html").body(s)) } // SERVICES #[allow(dead_code)] #[get("/r/{sub}")] async fn page(web::Path(sub): web::Path, params: web::Query) -> Result { match ¶ms.sort { Some(sort) => render(sub, sort.to_string()).await, None => render(sub, "hot".to_string()).await, } } // SUBREDDIT async fn subreddit(sub: &String) -> Result { // Build the Reddit JSON API url let url: String = format!("https://www.reddit.com/r/{}/about.json", sub); // Send a request to the url, receive JSON in response let res = request(url).await; let icon: String = String::from(res["data"]["community_icon"].as_str().unwrap()); //val(&data, "community_icon"); let icon_split: std::str::Split<&str> = icon.split("?"); let icon_parts: Vec<&str> = icon_split.collect(); let sub = Subreddit { name: val(&res, "display_name").await, title: val(&res, "title").await, description: val(&res, "public_description").await, icon: String::from(icon_parts[0]), }; Ok(sub) } // POSTS pub async fn posts(sub: String, sort: &String) -> Result> { // Build the Reddit JSON API url let url: String = format!("https://www.reddit.com/r/{}/{}.json", sub, sort); // Send a request to the url, receive JSON in response let res = request(url).await; // Fetch the list of posts from the JSON response let post_list = res["data"]["children"].as_array().unwrap(); let mut posts: Vec = Vec::new(); for post in post_list.iter() { let img = if val(post, "thumbnail").await.starts_with("https:/") { val(post, "thumbnail").await } else { String::new() }; let unix_time: i64 = post["data"]["created_utc"].as_f64().unwrap().round() as i64; let score = post["data"]["score"].as_i64().unwrap(); posts.push(Post { title: val(post, "title").await, community: val(post, "subreddit").await, body: String::new(), author: val(post, "author").await, score: if score > 1000 { format!("{}k", score / 1000) } else { score.to_string() }, media: img, url: val(post, "permalink").await, time: Utc.timestamp(unix_time, 0).format("%b %e '%y").to_string(), flair: Flair( val(post, "link_flair_text").await, val(post, "link_flair_background_color").await, if val(post, "link_flair_text_color").await == "dark" { "black".to_string() } else { "white".to_string() }, ), }); } Ok(posts) }