From 2c06ae1d8fd057244969ec1bd1298e135f672b74 Mon Sep 17 00:00:00 2001 From: spikecodes <19519553+spikecodes@users.noreply.github.com> Date: Tue, 17 Nov 2020 11:37:40 -0800 Subject: [PATCH] Create utils.rs for Utilities --- src/popular.rs | 5 ++-- src/post.rs | 30 +++---------------- src/subreddit.rs | 33 ++++----------------- src/user.rs | 63 +++++++++++++--------------------------- src/utils.rs | 54 ++++++++++++++++++++++++++++++++++ templates/popular.html | 2 +- templates/subreddit.html | 2 +- templates/user.html | 2 +- 8 files changed, 90 insertions(+), 101 deletions(-) create mode 100644 src/utils.rs diff --git a/src/popular.rs b/src/popular.rs index a01a88a..fc882d1 100644 --- a/src/popular.rs +++ b/src/popular.rs @@ -5,12 +5,13 @@ use serde::Deserialize; #[path = "subreddit.rs"] mod subreddit; +use subreddit::{posts, Post}; // STRUCTS #[derive(Template)] #[template(path = "popular.html", escape = "none")] struct PopularTemplate { - posts: Vec, + posts: Vec, sort: String, } @@ -21,7 +22,7 @@ pub struct Params { // RENDER async fn render(sub_name: String, sort: String) -> Result { - let posts: Vec = subreddit::posts(sub_name, &sort).await; + let posts: Vec = posts(sub_name, &sort).await; let s = PopularTemplate { posts: posts, sort: sort }.render().unwrap(); Ok(HttpResponse::Ok().content_type("text/html").body(s)) diff --git a/src/post.rs b/src/post.rs index f725e28..5abb9a1 100644 --- a/src/post.rs +++ b/src/post.rs @@ -4,6 +4,10 @@ use askama::Template; use chrono::{TimeZone, Utc}; use pulldown_cmark::{html, Options, Parser}; +#[path = "utils.rs"] +mod utils; +use utils::{Comment, Flair, Post, val}; + // STRUCTS #[derive(Template)] #[template(path = "post.html", escape = "none")] @@ -13,28 +17,6 @@ struct PostTemplate { sort: String, } -// Post flair with text, background color and foreground color -pub struct Flair(String, String, String); - -pub struct Post { - pub title: String, - pub community: String, - pub body: String, - pub author: String, - pub url: String, - pub score: String, - pub media: String, - pub time: String, - pub flair: Flair, -} - -pub struct Comment { - pub body: String, - pub author: String, - pub score: String, - pub time: String, -} - async fn render(id: String, sort: String) -> Result { println!("id: {}", id); let post: Post = fetch_post(&id).await; @@ -70,10 +52,6 @@ async fn sorted(web::Path((_sub, id, _title, sort)): web::Path<(String, String, } // UTILITIES -async fn val(j: &serde_json::Value, k: &str) -> String { - String::from(j["data"][k].as_str().unwrap_or("")) -} - async fn media(data: &serde_json::Value) -> String { let post_hint: &str = data["data"]["post_hint"].as_str().unwrap_or(""); let has_media: bool = data["data"]["media"].is_object(); diff --git a/src/subreddit.rs b/src/subreddit.rs index e9549ba..243ea08 100644 --- a/src/subreddit.rs +++ b/src/subreddit.rs @@ -3,6 +3,10 @@ use actix_web::{get, web, HttpResponse, Result}; use askama::Template; use chrono::{TimeZone, Utc}; +#[path = "utils.rs"] +mod utils; +pub use utils::{Flair, Post, Subreddit, val}; + // STRUCTS #[derive(Template)] #[template(path = "subreddit.html", escape = "none")] @@ -12,27 +16,6 @@ struct SubredditTemplate { sort: String, } -// Post flair with text, background color and foreground color -pub struct Flair(pub String, pub String, pub String); - -pub struct Post { - pub title: String, - pub community: String, - pub author: String, - pub score: String, - pub image: String, - pub url: String, - pub time: String, - pub flair: Flair, -} - -pub struct Subreddit { - pub name: String, - pub title: String, - pub description: String, - pub icon: 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; @@ -60,11 +43,6 @@ async fn sorted(web::Path((sub, sort)): web::Path<(String, String)>) -> Result String { - String::from(j["data"][k].as_str().unwrap_or("")) -} - // SUBREDDIT async fn subreddit(sub: &String) -> Subreddit { let url: String = format!("https://www.reddit.com/r/{}/about.json", sub); @@ -105,9 +83,10 @@ pub async fn posts(sub: String, sort: &String) -> Vec { 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() }, - image: img, + media: img, url: val(post, "permalink").await, time: Utc.timestamp(unix_time, 0).format("%b %e '%y").to_string(), flair: Flair( diff --git a/src/user.rs b/src/user.rs index 7e5f00d..a41eaca 100644 --- a/src/user.rs +++ b/src/user.rs @@ -3,6 +3,10 @@ use actix_web::{get, web, HttpResponse, Result}; use askama::Template; use chrono::{TimeZone, Utc}; +#[path = "utils.rs"] +mod utils; +use utils::{Flair, Post, User, val, nested_val}; + // STRUCTS #[derive(Template)] #[template(path = "user.html", escape = "none")] @@ -12,28 +16,6 @@ struct UserTemplate { sort: String, } -// Post flair with text, background color and foreground color -pub struct Flair(String, String, String); - -pub struct Post { - pub title: String, - pub community: String, - pub author: String, - pub score: String, - pub image: String, - pub url: String, - pub time: String, - pub flair: Flair, -} - -pub struct User { - pub name: String, - pub icon: String, - pub karma: i64, - pub banner: String, - pub description: String, -} - async fn render(username: String, sort: String) -> Result { let user: User = user(&username).await; let posts: Vec = posts(username, &sort).await; @@ -53,14 +35,6 @@ async fn sorted(web::Path((username, sort)): web::Path<(String, String)>) -> Res render(username, sort).await } -// UTILITIES -async fn user_val(j: &serde_json::Value, k: &str) -> String { - String::from(j["data"]["subreddit"][k].as_str().unwrap()) -} -async fn post_val(j: &serde_json::Value, k: &str) -> String { - String::from(j["data"][k].as_str().unwrap_or("Comment")) -} - // USER async fn user(name: &String) -> User { let url: String = format!("https://www.reddit.com/user/{}/about.json", name); @@ -70,10 +44,10 @@ async fn user(name: &String) -> User { User { name: name.to_string(), - icon: user_val(&data, "icon_img").await, + icon: nested_val(&data, "subreddit", "icon_img").await, karma: data["data"]["total_karma"].as_i64().unwrap(), - banner: user_val(&data, "banner_img").await, - description: user_val(&data, "public_description").await, + banner: nested_val(&data, "subreddit", "banner_img").await, + description: nested_val(&data, "subreddit", "public_description").await, } } @@ -88,25 +62,28 @@ async fn posts(sub: String, sort: &String) -> Vec { let mut posts: Vec = Vec::new(); for post in post_list.iter() { - let img = if post_val(post, "thumbnail").await.starts_with("https:/") { - post_val(post, "thumbnail").await + 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(); + let title = val(post, "title").await; + posts.push(Post { - title: post_val(post, "title").await, - community: post_val(post, "subreddit").await, - author: post_val(post, "author").await, + title: if title.is_empty() {"Comment".to_string()} else {title}, + 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() }, - image: img, - url: post_val(post, "permalink").await, + media: img, + url: val(post, "permalink").await, time: Utc.timestamp(unix_time, 0).format("%b %e '%y").to_string(), flair: Flair( - post_val(post, "link_flair_text").await, - post_val(post, "link_flair_background_color").await, - if post_val(post, "link_flair_text_color").await == "dark" { + 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() diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..9791a71 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,54 @@ +// Post flair with text, background color and foreground color +pub struct Flair(pub String, pub String, pub String); + +// Post containing content, metadata and media +pub struct Post { + pub title: String, + pub community: String, + pub body: String, + pub author: String, + pub url: String, + pub score: String, + pub media: String, + pub time: String, + pub flair: Flair, +} + +#[allow(dead_code)] +// Comment with content, post, score and data/time that it was posted +pub struct Comment { + pub body: String, + pub author: String, + pub score: String, + pub time: String, +} + +#[allow(dead_code)] +// User struct containing metadata about user +pub struct User { + pub name: String, + pub icon: String, + pub karma: i64, + pub banner: String, + pub description: String, +} + +#[allow(dead_code)] +// Subreddit struct containing metadata about community +pub struct Subreddit { + pub name: String, + pub title: String, + pub description: String, + pub icon: String, +} + +// val() function used to parse JSON from Reddit APIs +pub async fn val(j: &serde_json::Value, k: &str) -> String { + String::from(j["data"][k].as_str().unwrap_or("")) +} + +#[allow(dead_code)] +// nested_val() function used to parse JSON from Reddit APIs +pub async fn nested_val(j: &serde_json::Value, n: &str, k: &str) -> String { + String::from(j["data"][n][k].as_str().unwrap()) +} \ No newline at end of file diff --git a/templates/popular.html b/templates/popular.html index ed89285..5afedcd 100644 --- a/templates/popular.html +++ b/templates/popular.html @@ -44,7 +44,7 @@ {{ post.title }} - +
{% endfor %} diff --git a/templates/subreddit.html b/templates/subreddit.html index 42184d6..0213f4e 100644 --- a/templates/subreddit.html +++ b/templates/subreddit.html @@ -55,7 +55,7 @@ {{ post.title }} - +
{% endfor %} diff --git a/templates/user.html b/templates/user.html index 580c608..1c7bf37 100644 --- a/templates/user.html +++ b/templates/user.html @@ -57,7 +57,7 @@ {{ post.title }} - +
{% endfor %}