",
get_setting("REDLIB_PUSHSHIFT_FRONTEND").unwrap_or_else(|| String::from(crate::config::DEFAULT_PUSHSHIFT_FRONTEND)),
)
} else {
rewrite_urls(&body_html(post, "selftext", "selftext_html"))
};
// Build a post using data parsed from Reddit post API
Post {
id: val(post, "id"),
title: val(post, "title"),
community: val(post, "subreddit"),
body,
author: Author {
name: val(post, "author"),
flair: Flair {
flair_parts: FlairPart::parse(
post["data"]["author_flair_type"].as_str().unwrap_or_default(),
post["data"]["author_flair_richtext"].as_array(),
post["data"]["author_flair_text"].as_str(),
),
text: val(post, "link_flair_text"),
background_color: val(post, "author_flair_background_color"),
foreground_color: val(post, "author_flair_text_color"),
},
distinguished: val(post, "distinguished"),
advertiser: post["data"]["is_created_from_ads_ui"] == true,
},
permalink,
link_title: val(post, "link_title"),
poll,
score: format_num(score),
upvote_ratio: ratio as i64,
post_type,
media,
thumbnail: Media {
url: format_url(val(post, "thumbnail").as_str()),
alt_url: String::new(),
width: post["data"]["thumbnail_width"].as_i64().unwrap_or_default(),
height: post["data"]["thumbnail_height"].as_i64().unwrap_or_default(),
poster: String::new(),
download_name: String::new(),
needs_hls_for_audio: false,
},
flair: Flair {
flair_parts: FlairPart::parse(
post["data"]["link_flair_type"].as_str().unwrap_or_default(),
post["data"]["link_flair_richtext"].as_array(),
post["data"]["link_flair_text"].as_str(),
),
text: val(post, "link_flair_text"),
background_color: val(post, "link_flair_background_color"),
foreground_color: if val(post, "link_flair_text_color") == "dark" {
"black".to_string()
} else {
"white".to_string()
},
},
flags: Flags {
spoiler: post["data"]["spoiler"].as_bool().unwrap_or_default(),
nsfw: post["data"]["over_18"].as_bool().unwrap_or_default(),
stickied: post["data"]["stickied"].as_bool().unwrap_or_default() || post["data"]["pinned"].as_bool().unwrap_or(false),
},
domain: val(post, "domain"),
rel_time,
created,
created_ts,
num_duplicates: post["data"]["num_duplicates"].as_u64().unwrap_or(0),
comments: format_num(post["data"]["num_comments"].as_i64().unwrap_or_default()),
gallery,
awards,
nsfw: post["data"]["over_18"].as_bool().unwrap_or_default(),
ws_url: val(post, "websocket_url"),
out_url: post["data"]["url_overridden_by_dest"].as_str().map(|a| a.to_string()),
}
}
//
// FORMATTING
//
/// Grab a query parameter from a url
pub fn param(path: &str, value: &str) -> Option {
Some(
Url::parse(format!("https://libredd.it/{path}").as_str())
.ok()?
.query_pairs()
.into_owned()
.collect::>()
.get(value)?
.clone(),
)
}
/// Retrieve the value of a setting by name
pub fn setting(req: &Request, name: &str) -> String {
// Parse a cookie value from request
// If this was called with "subscriptions" and the "subscriptions" cookie has a value
if name == "subscriptions" && req.cookie("subscriptions").is_some() {
// Create subscriptions string
let mut subscriptions = String::new();
// Default subscriptions cookie
if req.cookie("subscriptions").is_some() {
subscriptions.push_str(req.cookie("subscriptions").unwrap().value());
}
// Start with first numbered subscription cookie
let mut subscriptions_number = 1;
// While whatever subscriptionsNUMBER cookie we're looking at has a value
while req.cookie(&format!("subscriptions{subscriptions_number}")).is_some() {
// Push whatever subscriptionsNUMBER cookie we're looking at into the subscriptions string
subscriptions.push_str(req.cookie(&format!("subscriptions{subscriptions_number}")).unwrap().value());
// Increment subscription cookie number
subscriptions_number += 1;
}
// Return the subscriptions cookies as one large string
subscriptions
}
// If this was called with "filters" and the "filters" cookie has a value
else if name == "filters" && req.cookie("filters").is_some() {
// Create filters string
let mut filters = String::new();
// Default filters cookie
if req.cookie("filters").is_some() {
filters.push_str(req.cookie("filters").unwrap().value());
}
// Start with first numbered filters cookie
let mut filters_number = 1;
// While whatever filtersNUMBER cookie we're looking at has a value
while req.cookie(&format!("filters{filters_number}")).is_some() {
// Push whatever filtersNUMBER cookie we're looking at into the filters string
filters.push_str(req.cookie(&format!("filters{filters_number}")).unwrap().value());
// Increment filters cookie number
filters_number += 1;
}
// Return the filters cookies as one large string
filters
}
// The above two still come to this if there was no existing value
else {
req
.cookie(name)
.unwrap_or_else(|| {
// If there is no cookie for this setting, try receiving a default from the config
if let Some(default) = get_setting(&format!("REDLIB_DEFAULT_{}", name.to_uppercase())) {
Cookie::new(name, default)
} else {
Cookie::from(name)
}
})
.value()
.to_string()
}
}
/// Retrieve the value of a setting by name or the default value
pub fn setting_or_default(req: &Request, name: &str, default: String) -> String {
let value = setting(req, name);
if value.is_empty() {
default
} else {
value
}
}
/// Detect and redirect in the event of a random subreddit
pub async fn catch_random(sub: &str, additional: &str) -> Result, String> {
if sub == "random" || sub == "randnsfw" {
Ok(redirect(&format!(
"/r/{}{additional}",
json(format!("/r/{sub}/about.json?raw_json=1"), false).await?["data"]["display_name"]
.as_str()
.unwrap_or_default()
)))
} else {
Err("No redirect needed".to_string())
}
}
static REGEX_URL_WWW: LazyLock = LazyLock::new(|| Regex::new(r"https?://www\.reddit\.com/(.*)").unwrap());
static REGEX_URL_OLD: LazyLock = LazyLock::new(|| Regex::new(r"https?://old\.reddit\.com/(.*)").unwrap());
static REGEX_URL_NP: LazyLock = LazyLock::new(|| Regex::new(r"https?://np\.reddit\.com/(.*)").unwrap());
static REGEX_URL_PLAIN: LazyLock = LazyLock::new(|| Regex::new(r"https?://reddit\.com/(.*)").unwrap());
static REGEX_URL_VIDEOS: LazyLock = LazyLock::new(|| Regex::new(r"https?://(?:cf\.)?v\.redd\.it/(.*)/(DASH|CMAF)_([0-9]{2,4}(\.mp4|$|\?source=fallback))").unwrap());
static REGEX_URL_VIDEOS_HLS: LazyLock = LazyLock::new(|| Regex::new(r"https?://(?:cf\.)?v\.redd\.it/(.+)/(HLSPlaylist\.m3u8)").unwrap());
static REGEX_URL_PACKAGED_MEDIA: LazyLock = LazyLock::new(|| Regex::new(r"https?://packaged-media\.redd\.it/(.*)").unwrap());
static REGEX_URL_EXTERNAL_PACKAGED_MEDIA: LazyLock = LazyLock::new(|| Regex::new(r"https?://external-packaged-media\.redd\.it/(.*)").unwrap());
static REGEX_URL_IMAGES: LazyLock = LazyLock::new(|| Regex::new(r"https?://i\.redd\.it/(.*)").unwrap());
static REGEX_URL_THUMBS_A: LazyLock = LazyLock::new(|| Regex::new(r"https?://a\.thumbs\.redditmedia\.com/(.*)").unwrap());
static REGEX_URL_THUMBS_B: LazyLock = LazyLock::new(|| Regex::new(r"https?://b\.thumbs\.redditmedia\.com/(.*)").unwrap());
static REGEX_URL_EMOJI: LazyLock = LazyLock::new(|| Regex::new(r"https?://emoji\.redditmedia\.com/(.*)/(.*)").unwrap());
static REGEX_URL_PREVIEW: LazyLock = LazyLock::new(|| Regex::new(r"https?://preview\.redd\.it/(.*)").unwrap());
static REGEX_URL_EXTERNAL_PREVIEW: LazyLock = LazyLock::new(|| Regex::new(r"https?://external\-preview\.redd\.it/(.*)").unwrap());
static REGEX_URL_STYLES: LazyLock = LazyLock::new(|| Regex::new(r"https?://styles\.redditmedia\.com/(.*)").unwrap());
static REGEX_URL_STATIC_MEDIA: LazyLock = LazyLock::new(|| Regex::new(r"https?://www\.redditstatic\.com/(.*)").unwrap());
static REGEX_URL_REDGIFS: LazyLock = LazyLock::new(|| Regex::new(r"https?://(?:www\.|v\d+\.)?redgifs\.com/watch/([^?#]*)").unwrap());
/// Direct urls to proxy if proxy is enabled
pub fn format_url(url: &str) -> String {
if url.is_empty() || url == "self" || url == "default" || url == "nsfw" || url == "spoiler" {
String::new()
} else {
Url::parse(url).map_or(url.to_string(), |parsed| {
let domain = parsed.domain().unwrap_or_default();
let capture = |regex: &Regex, format: &str, segments: i16| {
regex.captures(url).map_or(String::new(), |caps| match segments {
1 => [format, &caps[1]].join(""),
2 => [format, &caps[1], "/", &caps[2]].join(""),
3 => [format, &caps[1], "/", &caps[2], "/", &caps[3]].join(""),
_ => String::new(),
})
};
macro_rules! chain {
() => {
{
String::new()
}
};
( $first_fn:expr, $($other_fns:expr), *) => {
{
let result = $first_fn;
if result.is_empty() {
chain!($($other_fns,)*)
}
else
{
result
}
}
};
}
match domain {
"www.reddit.com" => capture(®EX_URL_WWW, "/", 1),
"old.reddit.com" => capture(®EX_URL_OLD, "/", 1),
"np.reddit.com" => capture(®EX_URL_NP, "/", 1),
"reddit.com" => capture(®EX_URL_PLAIN, "/", 1),
// The cookied backend may hand back cf.v.redd.it (Cloudflare-fronted) video URLs; they serve the same media
"v.redd.it" | "cf.v.redd.it" => chain!(capture(®EX_URL_VIDEOS, "/vid/", 3), capture(®EX_URL_VIDEOS_HLS, "/hls/", 2)),
"packaged-media.redd.it" => capture(®EX_URL_PACKAGED_MEDIA, "/packaged/", 1),
"external-packaged-media.redd.it" => capture(®EX_URL_EXTERNAL_PACKAGED_MEDIA, "/packaged-external/", 1),
"i.redd.it" => capture(®EX_URL_IMAGES, "/img/", 1),
"a.thumbs.redditmedia.com" => capture(®EX_URL_THUMBS_A, "/thumb/a/", 1),
"b.thumbs.redditmedia.com" => capture(®EX_URL_THUMBS_B, "/thumb/b/", 1),
"emoji.redditmedia.com" => capture(®EX_URL_EMOJI, "/emoji/", 2),
"preview.redd.it" => capture(®EX_URL_PREVIEW, "/preview/pre/", 1),
"external-preview.redd.it" => capture(®EX_URL_EXTERNAL_PREVIEW, "/preview/external-pre/", 1),
"styles.redditmedia.com" => capture(®EX_URL_STYLES, "/style/", 1),
"www.redditstatic.com" => capture(®EX_URL_STATIC_MEDIA, "/static/", 1),
"www.redgifs.com" if enable_redgifs() => capture(®EX_URL_REDGIFS, "/redgifs/", 1),
"redgifs.com" if enable_redgifs() => capture(®EX_URL_REDGIFS, "/redgifs/", 1),
d if enable_redgifs() && d.starts_with("v") && d.ends_with(".redgifs.com") => capture(®EX_URL_REDGIFS, "/redgifs/", 1),
_ => url.to_string(),
}
})
}
}
// Remove tracking query params
static URL_CLEANER: LazyLock> = LazyLock::new(|| Arc::new(UrlCleaner::from_embedded_rules().expect("Failed to initialize UrlCleaner")));
pub fn clean_url(url: String) -> String {
let is_external_url = match Url::parse(url.as_str()) {
Ok(parsed_url) => parsed_url.domain().is_some(),
_ => false,
};
let mut cleaned_url = url.clone();
if is_external_url {
cleaned_url = match URL_CLEANER.clear_single_url_str(cleaned_url.as_str()) {
Ok(cleaned_result) => cleaned_result.as_ref().to_owned(),
_ => cleaned_url,
}
}
cleaned_url
}
static REGEX_BULLET: LazyLock = LazyLock::new(|| Regex::new(r"(?m)^- (.*)$").unwrap());
static REGEX_BULLET_CONSECUTIVE_LINES: LazyLock = LazyLock::new(|| Regex::new(r"\n
").unwrap());
pub fn render_bullet_lists(input_text: &str) -> String {
// ref: https://stackoverflow.com/a/4902622
// First enclose each bullet with
tags
let text1 = REGEX_BULLET.replace_all(input_text, "
$1
").to_string();
// Then remove any consecutive
tags
REGEX_BULLET_CONSECUTIVE_LINES.replace_all(&text1, "").to_string()
}
// These are links we want to replace in-body
static REDDIT_REGEX: LazyLock = LazyLock::new(|| Regex::new(r#"href="(https|http|)://(www\.|old\.|np\.|amp\.|new\.|)(reddit\.com|redd\.it)/"#).unwrap());
// The second group stops `i.redd.it.example.org` from matching.
static REDDIT_PREVIEW_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"https?://(external-preview|preview|i)\.redd\.it([^\w.-]|$)").unwrap());
static REDDIT_EMOJI_REGEX: LazyLock = LazyLock::new(|| Regex::new(r#"https?://(?:www\.)?redditstatic\.com/[^\s"'<>]*"#).unwrap());
// A preview link up to its first ``, and the `
` if that closes the paragraph
static REDDIT_PREVIEW_PARAGRAPH_REGEX: LazyLock =
LazyLock::new(|| Regex::new(r#"
"#
)
})
.to_string()
}
// These links all follow a pattern of "https://reddit-econ-prod-assets-permanent.s3.amazonaws.com/asset-manager/SUBREDDIT_ID/RANDOM_FILENAME.png"
static REDDIT_EMOTE_LINK_REGEX: LazyLock = LazyLock::new(|| Regex::new(r#"https://reddit-econ-prod-assets-permanent.s3.amazonaws.com/asset-manager/(.*)"#).unwrap());
// These all follow a pattern of '"emote|SUBREDDIT_IT|NUMBER"', we want the number
static REDDIT_EMOTE_ID_NUMBER_REGEX: LazyLock = LazyLock::new(|| Regex::new(r#""emote\|.*\|(.*)""#).unwrap());
pub fn rewrite_emotes(media_metadata: &Value, comment: String) -> String {
/* Create the paths we'll use to look for our data inside the json.
Because we don't know the name of any given emote we use a wildcard to parse them. */
let link_path = JsonPath::parse("$[*].s.u").expect("valid JSON Path");
let id_path = JsonPath::parse("$[*].id").expect("valid JSON Path");
let size_path = JsonPath::parse("$[*].s.y").expect("valid JSON Path");
// Extract all of the results from those json paths
let link_nodes = media_metadata.json_path(&link_path);
let id_nodes = media_metadata.json_path(&id_path);
// Initialize our vectors
let mut id_vec = Vec::new();
let mut link_vec = Vec::new();
// Add the relevant data to each of our vectors so we can access it by number later
for current_id in id_nodes {
id_vec.push(current_id)
}
for current_link in link_nodes {
link_vec.push(current_link)
}
/* Set index to the length of link_vec.
This is one larger than we'll actually be looking at, but we correct that later */
let mut index = link_vec.len();
// Comment needs to be in scope for when we call rewrite_urls()
let mut comment = comment;
/* Loop until index hits zero.
This also prevents us from trying to do anything on an empty vector */
while index != 0 {
/* Subtract 1 from index to get the real index we should be looking at.
Then continue on each subsequent loop to continue until we hit the last entry in the vector.
This is how we get this to deal with multiple emotes in a single message and properly replace each ID with it's link */
index -= 1;
// Convert our current index in id_vec into a string so we can search through it with regex
let current_id = id_vec[index].to_string();
/* The ID number can be multiple lengths, so we capture it with regex.
We also want to only attempt anything when we get matches to avoid panicking */
if let Some(id_capture) = REDDIT_EMOTE_ID_NUMBER_REGEX.captures(¤t_id) {
// Format the ID to include the colons it has in the comment text
let id = format!(":{}:", &id_capture[1]);
// Convert current link to string to search through it with the regex
let link = link_vec[index].to_string();
// Make sure we only do operations when we get matches, otherwise we panic when trying to access the first match
if let Some(link_capture) = REDDIT_EMOTE_LINK_REGEX.captures(&link) {
/* Reddit sends a size for the image based on whether it's alone or accompanied by text.
It's a good idea and makes everything look nicer, so we'll do the same. */
let size = media_metadata.json_path(&size_path).first().unwrap().to_string();
// Replace the ID we found earlier in the comment with the respective image and it's link from the regex capture
let to_replace_with = format!(
"",
&link_capture[1]
);
// Inside the comment replace the ID we found with the string that will embed the image
comment = comment.replace(&id, &to_replace_with);
}
}
}
// render bullet (unordered) lists
comment = render_bullet_lists(&comment);
// Call rewrite_urls() to transform any other Reddit links
let comment = rewrite_urls(&comment);
if enable_giphy() {
rewrite_giphy_links(&comment)
} else {
comment
}
}
/// Format vote count to a string that will be displayed.
/// Append `m` and `k` for millions and thousands respectively, and
/// round to the nearest tenth.
pub fn format_num(num: i64) -> (String, String) {
let truncated = if num >= 10_000_000 || num <= -10_000_000 {
format!("{}m", num / 1_000_000)
} else if num >= 1_000_000 || num <= -1_000_000 {
format!("{:.1}m", num as f64 / 1_000_000.0)
} else if num >= 10000 || num <= -10000 {
format!("{}k", num / 1_000)
} else if num >= 1000 || num <= -1000 {
format!("{:.1}k", num as f64 / 1_000.0)
} else {
num.to_string()
};
(truncated, num.to_string())
}
/// Parse a relative and absolute time from a UNIX timestamp
pub fn time(created: f64) -> (String, String) {
if created == 0.0 {
return (String::new(), String::new());
}
let time = OffsetDateTime::from_unix_timestamp(created.round() as i64).unwrap_or(OffsetDateTime::UNIX_EPOCH);
let now = OffsetDateTime::now_utc();
let min = time.min(now);
let max = time.max(now);
let time_delta = max - min;
// If the time difference is more than a month, show full date
let mut rel_time = if time_delta > Duration::days(30) {
time.format(format_description!("[month repr:short] [day] '[year repr:last_two]")).unwrap_or_default()
// Otherwise, show relative date/time
} else if time_delta.whole_days() > 0 {
format!("{}d", time_delta.whole_days())
} else if time_delta.whole_hours() > 0 {
format!("{}h", time_delta.whole_hours())
} else {
format!("{}m", time_delta.whole_minutes())
};
if time_delta <= Duration::days(30) {
if now < time {
rel_time += " left";
} else {
rel_time += " ago";
}
}
(
rel_time,
time
.format(format_description!("[month repr:short] [day] [year], [hour]:[minute]:[second] UTC"))
.unwrap_or_default(),
)
}
/// val() function used to parse JSON from Reddit APIs
pub fn val(j: &Value, k: &str) -> String {
j["data"][k].as_str().unwrap_or_default().to_string()
}
//
// NETWORKING
//
pub fn template(t: &impl Template) -> Response {
Response::builder()
.status(200)
.header("content-type", "text/html")
.body(t.render().unwrap_or_default().into())
.unwrap_or_default()
}
pub fn redirect(path: &str) -> Response {
Response::builder()
.status(302)
.header("content-type", "text/html")
.header("Location", path)
.body(format!("Redirecting to {path}...").into())
.unwrap_or_default()
}
/// Renders a generic error landing page.
pub async fn error(req: Request, msg: &str) -> Result, String> {
error!("Error page rendered: {}", msg.split('|').next().unwrap_or_default());
let url = req.uri().to_string();
// "Title: detail | /reddit/path"
let (text, path) = msg.split_once(" | ").unwrap_or((msg, ""));
let (title, detail) = text.split_once(": ").unwrap_or((text, ""));
let blocked = crate::backends::is_blocked_error(msg);
let subreddits = if blocked { combined_feed_subreddits(path) } else { Vec::new() };
let (title, detail) = if subreddits.is_empty() {
(title, detail)
} else {
(
"Reddit blocked this combined feed (403)",
"Feeds that combine several subreddits, like your front page or r/a+b, can only be loaded through Reddit's JSON API, and Reddit refuses that API to this instance. Single subreddits still work, so you can open them one by one.",
)
};
let body = ErrorTemplate {
msg: title.to_string(),
detail: detail.to_string(),
reddit_url: if path.starts_with('/') {
format!("https://www.reddit.com{path}")
} else {
path.to_string()
},
blocked,
subreddits,
prefs: Preferences::new(&req),
url,
}
.render()
.unwrap_or_default();
Ok(Response::builder().status(404).header("content-type", "text/html").body(body.into()).unwrap_or_default())
}
/// The subreddits of a combined feed (`/r/a+b/...`), empty for a single one.
/// r/all is fetched as `/r/all+`, which leaves a single name.
fn combined_feed_subreddits(path: &str) -> Vec {
let Some(rest) = path.strip_prefix("/r/") else { return Vec::new() };
let names = rest.split(['/', '?', '.']).next().unwrap_or_default().replace("%2B", "+").replace("%2b", "+");
let subs: Vec = names.split('+').filter(|s| !s.is_empty()).map(str::to_string).collect();
if subs.len() < 2 {
return Vec::new();
}
subs
}
/// Renders a generic info landing page.
pub async fn info(req: Request, msg: &str) -> Result, String> {
let url = req.uri().to_string();
let body = InfoTemplate {
msg: msg.to_string(),
prefs: Preferences::new(&req),
url,
}
.render()
.unwrap_or_default();
Ok(Response::builder().status(200).header("content-type", "text/html").body(body.into()).unwrap_or_default())
}
/// Returns true if the config/env variable `REDLIB_SFW_ONLY` carries the
/// value `on`.
///
/// If this variable is set as such, the instance will operate in SFW-only
/// mode; all NSFW content will be filtered. Attempts to access NSFW
/// subreddits or posts or userpages for users Reddit has deemed NSFW will
/// be denied.
pub fn sfw_only() -> bool {
match get_setting("REDLIB_SFW_ONLY") {
Some(val) => val == "on",
None => false,
}
}
/// Returns true if the config/env variable REDLIB_ENABLE_RSS is set to "on".
/// If this variable is set as such, the instance will enable RSS feeds.
/// Otherwise, the instance will not provide RSS feeds.
pub fn enable_rss() -> bool {
match get_setting("REDLIB_ENABLE_RSS") {
Some(val) => val == "on",
None => false,
}
}
pub fn enable_redgifs() -> bool {
get_setting("REDLIB_ENABLE_REDGIFS").is_none_or(|val| val != "off")
}
pub fn enable_giphy() -> bool {
get_setting("REDLIB_ENABLE_GIPHY").is_none_or(|val| val != "off")
}
pub fn enable_scrape_fallback() -> bool {
get_setting("REDLIB_ENABLE_SCRAPE_FALLBACK").is_none_or(|val| val != "off")
}
pub fn enable_gql() -> bool {
get_setting("REDLIB_ENABLE_GQL").is_none_or(|val| val != "off")
}
/// Extra "more comments" requests a scraped post page makes up front.
pub fn scrape_comment_prefetch() -> usize {
get_setting("REDLIB_SCRAPE_COMMENT_PREFETCH").and_then(|val| val.parse().ok()).unwrap_or(0)
}
/// Returns true if the config/env variable `REDLIB_ROBOTS_DISABLE_INDEXING` carries the
/// value `on`.
///
/// If this variable is set as such, the instance will block all robots in robots.txt and
/// insert the noindex, nofollow meta tag on every page.
pub fn disable_indexing() -> bool {
match get_setting("REDLIB_ROBOTS_DISABLE_INDEXING") {
Some(val) => val == "on",
None => false,
}
}
/// Returns the currently configured source code URL to display in the footer.
/// Defaults to the upstream Github repository URL when not explicitly configured.
pub fn get_source_url() -> String {
get_setting("REDLIB_SOURCE_URL").unwrap_or("https://github.com/Project516/redlib".into())
}
/// Display name of a theme; its id stays the file name.
pub fn theme_label(theme: &str) -> &str {
match theme {
"system" => "System",
"black" => "Black",
"catppuccinFrappe" => "Catppuccin Frappé",
"catppuccinLatte" => "Catppuccin Latte",
"catppuccinMacchiato" => "Catppuccin Macchiato",
"catppuccinMocha" => "Catppuccin Mocha",
"dark" => "Dark",
"doomone" => "Doom One",
"dracula" => "Dracula",
"gold" => "Gold",
"gruvboxdark" => "Gruvbox Dark",
"gruvboxlight" => "Gruvbox Light",
"icebergDark" => "Iceberg Dark",
"laserwave" => "LaserWave",
"libredditBlack" => "Libreddit Black",
"libredditDark" => "Libreddit Dark",
"libredditLight" => "Libreddit Light",
"light" => "Light",
"midnightPurple" => "Midnight Purple",
"nord" => "Nord",
"rosebox" => "Rosebox",
"tokyoNight" => "Tokyo Night",
"violet" => "Violet",
_ => theme,
}
}
pub fn short_git_hash() -> &'static str {
let hash = env!("GIT_HASH").trim();
hash.get(..7).unwrap_or(hash)
}
/// Determines if a request should redirect to a NSFW landing gate.
pub fn should_be_nsfw_gated(req: &Request, _req_url: &str) -> bool {
(setting(req, "show_nsfw") != "on") || sfw_only()
}
/// Renders the landing page for NSFW content when the user has not enabled
/// "show NSFW posts" in settings.
pub async fn nsfw_landing(req: Request, req_url: String) -> Result, String> {
let res_type: ResourceType;
// Determine from the request URL if the resource is a subreddit, a user
// page, or a post.
let resource: String = if !req.param("name").unwrap_or_default().is_empty() {
res_type = ResourceType::User;
req.param("name").unwrap_or_default()
} else if !req.param("id").unwrap_or_default().is_empty() {
res_type = ResourceType::Post;
req.param("id").unwrap_or_default()
} else {
res_type = ResourceType::Subreddit;
req.param("sub").unwrap_or_default()
};
let body = NSFWLandingTemplate {
res: resource,
res_type,
prefs: Preferences::new(&req),
url: req_url,
}
.render()
.unwrap_or_default();
Ok(Response::builder().status(403).header("content-type", "text/html").body(body.into()).unwrap_or_default())
}
/// Returns the last (non-empty) segment of a path string
pub fn url_path_basename(path: &str) -> String {
let url_result = Url::parse(format!("https://libredd.it/{path}").as_str());
match url_result {
Ok(mut url) => {
url.path_segments_mut().unwrap().pop_if_empty();
url.path_segments().unwrap().next_back().unwrap().to_string()
}
Err(_) => path.to_string(),
}
}
/// Returns the absolute URL of a post, as needed by RSS feeds
pub fn get_post_url(post: &Post) -> String {
match post.post_type.as_str() {
"image" | "gallery" | "gif" | "video" => return to_absolute_url(&post.permalink),
_ => {}
}
if let Some(out_url) = &post.out_url {
return if out_url.starts_with("/r/") { to_absolute_url(out_url) } else { out_url.clone() };
}
to_absolute_url(&post.permalink)
}
/// Returns an absolute URL given a relative URL, as needed by RSS feeds
pub fn to_absolute_url(relative_path: &str) -> String {
format!("{}{}", config::get_setting("REDLIB_FULL_URL").unwrap_or_default(), relative_path)
}
// =====================================================
// RSS Feed Helpers
// =====================================================
/// Sorts that can follow a subreddit or the front page in a feed URL, e.g. `/r/rust/top.rss`.
pub const RSS_LISTING_SORTS: [&str; 6] = ["hot", "new", "top", "rising", "controversial", "best"];
/// Listings that can follow a user in a feed URL, e.g. `/user/spez/comments.rss`.
pub const RSS_USER_LISTINGS: [&str; 3] = ["overview", "submitted", "comments"];
/// Path of the HTML page a feed mirrors: `/r/rust/top.rss` and `/r/rust/top/.rss` both become `/r/rust/top`.
pub fn rss_page_path(req: &Request) -> String {
let path = req.uri().path();
let path = path.strip_suffix(".rss").unwrap_or(path).trim_end_matches('/');
if path.is_empty() {
"/".to_string()
} else {
path.to_string()
}
}
/// Absolute link to the HTML page a feed mirrors, including the feed's query string.
pub fn rss_page_link(req: &Request) -> String {
let path = rss_page_path(req);
match req.uri().query() {
Some(query) => to_absolute_url(&format!("{path}?{query}")),
None => to_absolute_url(&path),
}
}
/// Builds the RSS feed URL matching a Redlib page, for the RSS buttons and feed autodiscovery.
/// Keeps the query parameters that change what the feed contains (sort, timeframe, search query)
/// and drops pagination. Returns `None` if RSS is disabled or the page has no feed.
pub fn rss_feed_url(url: &str, prefs: &Preferences) -> Option {
if !enable_rss() {
return None;
}
page_feed_url(url, &prefs.front_page, &prefs.subscriptions, &prefs.post_sort)
}
/// `post_sort` is the sort a listing page shows when its URL has none; the feed URL names it explicitly.
fn page_feed_url(url: &str, front_page: &str, subscriptions: &[String], post_sort: &str) -> Option {
let parsed = Url::parse(&format!("https://redlib.invalid{url}")).ok()?;
let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();
let query: Vec<(String, String)> = parsed.query_pairs().into_owned().collect();
let keep_query = |keys: &[&str]| -> String {
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
for (k, v) in &query {
if keys.contains(&k.as_str()) && !v.is_empty() {
serializer.append_pair(k, v);
}
}
let query = serializer.finish();
if query.is_empty() {
query
} else {
format!("?{query}")
}
};
let listing_query = || keep_query(&["sort", "t"]);
let default_sort = Some(post_sort).filter(|s| RSS_LISTING_SORTS.contains(s));
let sorted = |base: &str, sort: Option<&str>| match sort {
Some(sort) => format!("{base}/{sort}.rss"),
None => format!("{base}.rss"),
};
// Search for subreddits and users has no posts to put in a feed
if segments.last() == Some(&"search") && query.iter().any(|(k, v)| k == "type" && v != "link") {
return None;
}
let path = match segments.as_slice() {
// Front page. Feed readers don't send cookies, so point at the user's front page or subscriptions directly.
[] | [_] if segments.first().is_none_or(|s| RSS_LISTING_SORTS.contains(s)) => {
let sort = segments.first().copied().or(default_sort);
let sub = if !front_page.is_empty() && front_page != "default" {
front_page.to_string()
} else {
subscriptions.join("+")
};
let feed = match (sub.is_empty(), sort) {
(true, Some(sort)) => format!("/{sort}.rss"),
(true, None) => "/.rss".to_string(),
(false, sort) => sorted(&format!("/r/{sub}"), sort),
};
feed + &listing_query()
}
["search"] => format!("/search.rss{}", keep_query(&["q", "sort", "t", "restrict_sr"])),
["r", sub, "search"] => format!("/r/{sub}/search.rss{}", keep_query(&["q", "sort", "t", "restrict_sr"])),
["r", sub] => sorted(&format!("/r/{sub}"), default_sort) + &listing_query(),
["r", sub, sort] if RSS_LISTING_SORTS.contains(sort) => sorted(&format!("/r/{sub}"), Some(sort)) + &listing_query(),
["r", sub, "comments", id, ..] => format!("/r/{sub}/comments/{id}.rss{}", keep_query(&["sort"])),
["comments", id, ..] => format!("/comments/{id}.rss{}", keep_query(&["sort"])),
["user" | "u", name] => format!("/user/{name}.rss{}", listing_query()),
["user" | "u", name, listing] if RSS_USER_LISTINGS.contains(listing) => format!("/user/{name}/{listing}.rss{}", listing_query()),
_ => return None,
};
Some(path)
}
/// Converts listing posts to feed items. NSFW items are dropped on SFW-only instances.
pub fn build_rss_items(posts: &[Post]) -> Vec {
posts.iter().filter(|post| !(sfw_only() && post.nsfw)).map(build_rss_item).collect()
}
/// Serializes a feed into an HTTP response.
pub fn rss_response(channel: &Channel) -> Response {
let mut res = Response::new(Body::from(channel.to_string().into_bytes()));
res
.headers_mut()
.insert(hyper::header::CONTENT_TYPE, hyper::header::HeaderValue::from_static("application/rss+xml"));
res
}
/// Build an RSS item from a Post, with proper enclosure, GUID, and media embed.
/// Comments in a listing (e.g. `/r/rust/comments.json`) come through as Posts without a title.
pub fn build_rss_item(post: &Post) -> Item {
if post.title.is_empty() && !post.link_title.is_empty() {
return build_rss_comment_item(&post.author.name, &post.link_title, &post.permalink, &post.body, post.created_ts);
}
let mut item = Item {
title: Some(post.title.to_string()),
link: Some(to_absolute_url(&post.permalink)),
author: Some(post.author.name.to_string()),
pub_date: Some(DateTime::from_timestamp(post.created_ts as i64, 0).unwrap_or_default().to_rfc2822()),
guid: Some(Guid {
value: to_absolute_url(&post.permalink),
permalink: true,
}),
..Default::default()
};
// Build description
let description_str = match post.post_type.as_str() {
"gallery" => format!("Gallery with {} images", to_absolute_url(&post.permalink), post.gallery.len()),
_ => format!("Comments", to_absolute_url(&post.permalink)),
};
item.set_description(description_str.clone());
// Build content:encoded — embed media + body
let image_html = build_media_html(post);
let content = if !image_html.is_empty() || !post.body.is_empty() {
format!("{}{}", image_html, absolute_html_urls(&post.body))
} else {
description_str
};
item.set_content(content);
// Set enclosure for media posts
if let Some(enclosure) = get_rss_image(post) {
item.set_enclosure(enclosure);
}
item
}
/// Build an RSS item for a comment. `body` is the comment's HTML with URLs already rewritten.
pub fn build_rss_comment_item(author: &str, link_title: &str, permalink: &str, body: &str, created_ts: u64) -> Item {
let link = to_absolute_url(permalink);
let body = absolute_html_urls(body);
Item {
title: Some(format!("u/{author} on {link_title}")),
link: Some(link.clone()),
author: Some(author.to_string()),
pub_date: Some(DateTime::from_timestamp(created_ts as i64, 0).unwrap_or_default().to_rfc2822()),
guid: Some(Guid { value: link, permalink: true }),
description: Some(body.clone()),
content: Some(body),
..Default::default()
}
}
static RELATIVE_HTML_URL: LazyLock = LazyLock::new(|| Regex::new(r#"(href|src)="/([^/])"#).unwrap());
/// Feed readers don't know the instance's address, so point Redlib's relative links
/// (`/r/...`, `/preview/...`) at `REDLIB_FULL_URL`. Protocol-relative `//host` links are left alone.
fn absolute_html_urls(html: &str) -> String {
prefix_relative_urls(html, &config::get_setting("REDLIB_FULL_URL").unwrap_or_default())
}
fn prefix_relative_urls(html: &str, base: &str) -> String {
let base = base.trim_end_matches('/');
if base.is_empty() {
return html.to_string();
}
RELATIVE_HTML_URL.replace_all(html, format!("$1=\"{base}/$2").as_str()).into_owned()
}
/// Generate the HTML for embedding media (images/videos) in RSS content
/// Uses proxied Redlib URLs and inline styles to fit the reader window
fn build_media_html(post: &Post) -> String {
match post.post_type.as_str() {
"image" => {
let url = to_absolute_url(&post.media.url);
format!(" ", url, url)
}
"gallery" => post
.gallery
.iter()
.map(|media| {
let url = to_absolute_url(&media.url);
format!(" ", url, url)
})
.collect::>()
.join("\n"),
"video" | "gif" => {
let poster = to_absolute_url(&post.media.poster);
let video_url = to_absolute_url(&post.media.url);
format!(
" ",
poster, video_url
)
}
_ => String::new(),
}
}
/// Create an RSS enclosure for the first image of a post
/// Uses proxied Redlib URLs
fn get_rss_image(post: &Post) -> Option {
let image_url = match post.post_type.as_str() {
"image" => Some(to_absolute_url(&post.media.url)),
"gallery" => post.gallery.first().map(|media| to_absolute_url(&media.url)),
"gif" | "video" => Some(to_absolute_url(&post.media.poster)),
_ => None,
};
image_url.map(|url| {
let mut enclosure = Enclosure::default();
enclosure.set_mime_type(get_mime_type(&url));
enclosure.set_url(url);
enclosure.set_length("0");
enclosure
})
}
/// Determines the MIME type based on file extension in a URL
fn get_mime_type(url: &str) -> &'static str {
let path = url.split('?').next().unwrap_or(url);
let extension = path.rsplit('.').next().unwrap_or("").to_lowercase();
match extension.as_str() {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"webp" => "image/webp",
"svg" => "image/svg+xml",
_ => "application/octet-stream",
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_time_unknown_is_empty() {
// A missing timestamp parses as 0; show nothing instead of Jan 01 1970
assert_eq!(super::time(0.0), (String::new(), String::new()));
}
#[test]
fn test_combined_feed_subreddits() {
assert_eq!(
super::combined_feed_subreddits("/r/news%2Bworldnews%2Bu_spez/new.json?&raw_json=1"),
["news", "worldnews", "u_spez"]
);
assert_eq!(super::combined_feed_subreddits("/r/rust+linux/hot.json"), ["rust", "linux"]);
assert!(super::combined_feed_subreddits("/r/news/hot.json").is_empty());
assert!(super::combined_feed_subreddits("/r/all+/hot.json").is_empty());
assert!(super::combined_feed_subreddits("/comments/abc.json").is_empty());
}
use super::{
deflate_compress, deflate_decompress, format_num, format_url, normalize_share_base, render_bullet_lists, rewrite_emotes, rewrite_urls, share_base, url_path_basename,
Post, Preferences,
};
use super::{page_feed_url, prefix_relative_urls, Media};
use serde_json::{json, Value};
#[test]
fn test_markdown_highlights_fenced_code() {
let html = crate::utils::markdown_html("text\n\n```rust\nlet x = 1;\n```\n\n```nope\n\n```");
assert!(html.starts_with("
text
"));
assert!(html.contains("let"));
// Unknown languages stay plain, but escaped
assert!(html.contains("
<b>\n
"));
}
#[test]
fn test_markdown_shows_html_as_text() {
let html = crate::utils::markdown_html("\n\n```\nx\n```\n\nhi ");
assert!(!html.contains("