Add subreddits to search results

This commit is contained in:
robrobinbin 2021-01-14 19:22:50 +01:00
parent 33c8bdffb9
commit a85a4278f6
4 changed files with 102 additions and 1 deletions

View file

@ -27,6 +27,12 @@ async fn favicon() -> HttpResponse {
.body(include_bytes!("../static/favicon.ico").as_ref())
}
async fn thumbnail() -> HttpResponse {
HttpResponse::Ok()
.header("Cache-Control", "public, max-age=1209600, s-maxage=86400")
.body(include_bytes!("../static/thumbnail.svg").as_ref())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let mut address = "0.0.0.0:8080".to_string();
@ -66,6 +72,7 @@ async fn main() -> std::io::Result<()> {
// GENERAL SERVICES
.route("/style.css/", web::get().to(style))
.route("/favicon.ico/", web::get().to(favicon))
.route("/thumbnail.svg/", web::get().to(thumbnail))
.route("/robots.txt/", web::get().to(robots))
// SETTINGS SERVICE
.route("/settings/", web::get().to(settings::get))

View file

@ -1,5 +1,5 @@
// CRATES
use crate::utils::{error, fetch_posts, param, prefs, Post, Preferences};
use crate::utils::{error, fetch_posts, param, prefs, Post, Preferences, request, val};
use actix_web::{HttpRequest, HttpResponse};
use askama::Template;
@ -13,10 +13,19 @@ struct SearchParams {
restrict_sr: String,
}
// STRUCTS
struct Subreddit {
name: String,
url: String,
description: String,
subscribers: i64,
}
#[derive(Template)]
#[template(path = "search.html", escape = "none")]
struct SearchTemplate {
posts: Vec<Post>,
subreddits: Vec<Subreddit>,
sub: String,
params: SearchParams,
prefs: Preferences,
@ -31,11 +40,42 @@ pub async fn find(req: HttpRequest) -> HttpResponse {
param(&path, "sort")
};
let sub = req.match_info().get("sub").unwrap_or("").to_string();
let mut subreddits: Vec<Subreddit> = Vec::new();
if param(&path, "restrict_sr") == "" {
let subreddit_search_path = format!("/subreddits/search.json?q={}&limit=3", param(&path, "q"));
let res;
let subreddit_list;
// Send a request to the url
match request(&subreddit_search_path).await {
// If success, receive JSON in response
Ok(response) => {
res = response;
subreddit_list = res["data"]["children"].as_array();
}
// If the Reddit API returns an error, exit this function
Err(_msg) => {subreddit_list = None;}
}
// For each subreddit from subreddit list
if !subreddit_list.is_none() {
for subreddit in subreddit_list.unwrap() {
subreddits.push(Subreddit {
name: val(subreddit, "display_name_prefixed"),
url: val(subreddit, "url"),
description: val(subreddit, "public_description"),
subscribers: subreddit["data"]["subscribers"].as_u64().unwrap_or_default() as i64,
});
}
}
}
match fetch_posts(&path, String::new()).await {
Ok((posts, after)) => HttpResponse::Ok().content_type("text/html").body(
SearchTemplate {
posts,
subreddits,
sub,
params: SearchParams {
q: param(&path, "q"),