Search - support a wider variety of reddit links.

Add once cell dependency for static regex support (avoid compiling the
same regex multiple times).
All search queries are now matched against a regex (provided by @Daniel-Valentine)
that determines if it is a reddit link. If it is, the prefix specifying
the reddit instance will be truncated from the query that will then be
processed normally.
For example, the query 'https://www.reddit.com/r/rust' will be treated
the same way as the query 'r/rust'.
This commit is contained in:
gmnsii 2022-12-19 13:17:42 -08:00
parent e4354d2320
commit da6b716e75
No known key found for this signature in database
GPG Key ID: 13B5ECF7DDFDA0DC
3 changed files with 8 additions and 6 deletions

1
Cargo.lock generated
View File

@ -677,6 +677,7 @@ dependencies = [
"hyper-rustls",
"libflate",
"lipsum",
"once_cell",
"percent-encoding",
"regex",
"route-recognizer",

View File

@ -27,6 +27,7 @@ url = "2.3.1"
rust-embed = { version = "6.4.2", features = ["include-exclude"] }
libflate = "1.2.0"
brotli = { version = "3.3.4", features = ["std"] }
once_cell = "1.16.0"
[dev-dependencies]
lipsum = "0.8.2"

View File

@ -7,6 +7,8 @@ use crate::{
};
use askama::Template;
use hyper::{Body, Request, Response};
use once_cell::sync::Lazy;
use regex::Regex;
// STRUCTS
struct SearchParams {
@ -46,17 +48,15 @@ struct SearchTemplate {
all_posts_hidden_nsfw: bool,
}
// Regex matched against search queries to determine if they are reddit urls.
static REDDIT_URL_MATCH: Lazy<Regex> = Lazy::new(|| Regex::new(r"^https?://([^\./]+\.)*reddit.com/").unwrap());
// SERVICES
pub async fn find(req: Request<Body>) -> Result<Response<Body>, String> {
let nsfw_results = if setting(&req, "show_nsfw") == "on" { "&include_over_18=on" } else { "" };
let path = format!("{}.json?{}{}&raw_json=1", req.uri().path(), req.uri().query().unwrap_or_default(), nsfw_results);
let mut query = param(&path, "q").unwrap_or_default();
if query.starts_with("https://www.reddit.com/") {
query = query.trim_start_matches("https://www.reddit.com/").to_string();
} else if query.starts_with("https://old.reddit.com/") {
query = query.trim_start_matches("https://old.reddit.com/").to_string();
}
query = REDDIT_URL_MATCH.replace(&query, "").to_string();
if query.is_empty() {
return Ok(redirect("/".to_string()));