Rewrite + Searching

This commit is contained in:
spikecodes 2020-12-31 15:54:13 -08:00
parent c7282520cd
commit a6dc7ee043
17 changed files with 342 additions and 262 deletions

View file

@ -3,6 +3,7 @@
//
use chrono::{TimeZone, Utc};
use serde_json::{from_str, Value};
use url::Url;
// use surf::{client, get, middleware::Redirect};
#[cfg(feature = "proxy")]
@ -16,7 +17,7 @@ pub struct Flair(pub String, pub String, pub String);
// Post flags with nsfw and stickied
pub struct Flags {
pub nsfw: bool,
pub stickied: bool
pub stickied: bool,
}
// Post containing content, metadata and media
@ -72,6 +73,7 @@ pub struct Subreddit {
#[derive(serde::Deserialize)]
pub struct Params {
pub t: Option<String>,
pub q: Option<String>,
pub sort: Option<String>,
pub after: Option<String>,
pub before: Option<String>,
@ -88,6 +90,13 @@ pub struct ErrorTemplate {
// FORMATTING
//
// Grab a query param from a url
pub async fn param(path: &String, value: &str) -> String {
let url = Url::parse(format!("https://reddit.com/{}", path).as_str()).unwrap();
let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect();
pairs.get(value).unwrap_or(&String::new()).to_owned()
}
// Direct urls to proxy if proxy is enabled
pub async fn format_url(url: String) -> String {
if url.is_empty() {
@ -127,9 +136,9 @@ pub async fn nested_val(j: &serde_json::Value, n: &str, k: &str) -> String {
}
// Fetch posts of a user or subreddit
pub async fn fetch_posts(url: String, fallback_title: String) -> Result<(Vec<Post>, String), &'static str> {
pub async fn fetch_posts(path: String, fallback_title: String) -> Result<(Vec<Post>, String), &'static str> {
// Send a request to the url, receive JSON in response
let req = request(url.clone()).await;
let req = request(path.clone()).await;
// If the Reddit API returns an error, exit this function
if req.is_err() {
@ -178,14 +187,14 @@ pub async fn fetch_posts(url: String, fallback_title: String) -> Result<(Vec<Pos
),
flags: Flags {
nsfw: post["data"]["over_18"].as_bool().unwrap_or(false),
stickied: post["data"]["stickied"].as_bool().unwrap_or(false)
stickied: post["data"]["stickied"].as_bool().unwrap_or(false),
},
url: val(post, "permalink").await,
time: Utc.timestamp(unix_time, 0).format("%b %e '%y").to_string(),
});
}
dbg!(url);
dbg!(path);
Ok((posts, res["data"]["after"].as_str().unwrap_or("").to_string()))
}
@ -195,8 +204,8 @@ pub async fn fetch_posts(url: String, fallback_title: String) -> Result<(Vec<Pos
//
// Make a request to a Reddit API and parse the JSON response
pub async fn request(mut url: String) -> Result<serde_json::Value, &'static str> {
url = format!("https://www.reddit.com/{}", url);
pub async fn request(path: String) -> Result<serde_json::Value, &'static str> {
let url = format!("https://www.reddit.com/{}", path);
// --- actix-web::client ---
// let client = actix_web::client::Client::default();