Create utils.rs for Utilities

This commit is contained in:
spikecodes 2020-11-17 11:37:40 -08:00
parent 4350d5b7b3
commit 2c06ae1d8f
8 changed files with 90 additions and 101 deletions

View File

@ -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<subreddit::Post>,
posts: Vec<Post>,
sort: String,
}
@ -21,7 +22,7 @@ pub struct Params {
// RENDER
async fn render(sub_name: String, sort: String) -> Result<HttpResponse> {
let posts: Vec<subreddit::Post> = subreddit::posts(sub_name, &sort).await;
let posts: Vec<Post> = posts(sub_name, &sort).await;
let s = PopularTemplate { posts: posts, sort: sort }.render().unwrap();
Ok(HttpResponse::Ok().content_type("text/html").body(s))

View File

@ -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<HttpResponse> {
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();

View File

@ -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<HttpResponse> {
let mut sub: Subreddit = subreddit(&sub_name).await;
let posts: Vec<Post> = posts(sub_name, &sort).await;
@ -60,11 +43,6 @@ async fn sorted(web::Path((sub, sort)): web::Path<(String, String)>) -> Result<H
render(sub, sort).await
}
// UTILITIES
async fn val(j: &serde_json::Value, k: &str) -> 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<Post> {
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(

View File

@ -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<HttpResponse> {
let user: User = user(&username).await;
let posts: Vec<Post> = 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<Post> {
let mut posts: Vec<Post> = 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()

54
src/utils.rs Normal file
View File

@ -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())
}

View File

@ -44,7 +44,7 @@
<a href="{{ post.url }}">{{ post.title }}</a>
</h3>
</div>
<img class="post_thumbnail" src="{{ post.image }}">
<img class="post_thumbnail" src="{{ post.media }}">
</div><br>
{% endfor %}
</main>

View File

@ -55,7 +55,7 @@
<a href="{{ post.url }}">{{ post.title }}</a>
</h3>
</div>
<img class="post_thumbnail" src="{{ post.image }}">
<img class="post_thumbnail" src="{{ post.media }}">
</div><br>
{% endfor %}
</main>

View File

@ -57,7 +57,7 @@
<a href="{{ post.url }}">{{ post.title }}</a>
</h3>
</div>
<img class="post_thumbnail" src="{{ post.image }}">
<img class="post_thumbnail" src="{{ post.media }}">
</div><br>
{% endfor %}
</main>