2020-11-21 19:05:27 +13:00
|
|
|
//
|
|
|
|
// CRATES
|
|
|
|
//
|
2021-01-01 18:03:44 +13:00
|
|
|
use askama::Template;
|
2021-02-08 14:56:06 +13:00
|
|
|
use cached::proc_macro::cached;
|
2021-01-03 07:58:21 +13:00
|
|
|
use regex::Regex;
|
2021-02-23 13:43:32 +13:00
|
|
|
use serde_json::{from_str, Error, Value};
|
2021-01-09 14:35:04 +13:00
|
|
|
use std::collections::HashMap;
|
2021-02-10 06:38:52 +13:00
|
|
|
use tide::{http::url::Url, http::Cookie, Request, Response};
|
2021-01-14 09:52:00 +13:00
|
|
|
use time::{Duration, OffsetDateTime};
|
2020-11-21 19:05:27 +13:00
|
|
|
|
2021-01-13 10:43:03 +13:00
|
|
|
// Post flair with content, background color and foreground color
|
2021-01-14 09:52:00 +13:00
|
|
|
pub struct Flair {
|
|
|
|
pub flair_parts: Vec<FlairPart>,
|
2021-02-21 10:59:16 +13:00
|
|
|
pub text: String,
|
2021-01-13 10:43:03 +13:00
|
|
|
pub background_color: String,
|
|
|
|
pub foreground_color: String,
|
|
|
|
}
|
|
|
|
|
2021-01-15 12:13:52 +13:00
|
|
|
// Part of flair, either emoji or text
|
2021-01-14 09:52:00 +13:00
|
|
|
pub struct FlairPart {
|
|
|
|
pub flair_part_type: String,
|
2021-01-13 10:43:03 +13:00
|
|
|
pub value: String,
|
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
impl FlairPart {
|
|
|
|
pub fn parse(flair_type: &str, rich_flair: Option<&Vec<Value>>, text_flair: Option<&str>) -> Vec<Self> {
|
|
|
|
// Parse type of flair
|
|
|
|
match flair_type {
|
|
|
|
// If flair contains emojis and text
|
|
|
|
"richtext" => match rich_flair {
|
|
|
|
Some(rich) => rich
|
|
|
|
.iter()
|
|
|
|
// For each part of the flair, extract text and emojis
|
|
|
|
.map(|part| {
|
|
|
|
let value = |name: &str| part[name].as_str().unwrap_or_default();
|
|
|
|
Self {
|
|
|
|
flair_part_type: value("e").to_string(),
|
|
|
|
value: match value("e") {
|
|
|
|
"text" => value("t").to_string(),
|
|
|
|
"emoji" => format_url(value("u")),
|
|
|
|
_ => String::new(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect::<Vec<Self>>(),
|
|
|
|
None => Vec::new(),
|
|
|
|
},
|
|
|
|
// If flair contains only text
|
|
|
|
"text" => match text_flair {
|
|
|
|
Some(text) => vec![Self {
|
|
|
|
flair_part_type: "text".to_string(),
|
|
|
|
value: text.to_string(),
|
|
|
|
}],
|
|
|
|
None => Vec::new(),
|
|
|
|
},
|
|
|
|
_ => Vec::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-17 12:02:24 +13:00
|
|
|
pub struct Author {
|
|
|
|
pub name: String,
|
|
|
|
pub flair: Flair,
|
|
|
|
pub distinguished: String,
|
|
|
|
}
|
|
|
|
|
2020-12-30 16:01:02 +13:00
|
|
|
// Post flags with nsfw and stickied
|
|
|
|
pub struct Flags {
|
|
|
|
pub nsfw: bool,
|
2021-01-01 12:54:13 +13:00
|
|
|
pub stickied: bool,
|
2020-12-30 16:01:02 +13:00
|
|
|
}
|
2020-11-18 08:37:40 +13:00
|
|
|
|
2021-01-18 09:58:12 +13:00
|
|
|
pub struct Media {
|
|
|
|
pub url: String,
|
|
|
|
pub width: i64,
|
|
|
|
pub height: i64,
|
2021-02-08 13:22:14 +13:00
|
|
|
pub poster: String,
|
2021-01-18 09:58:12 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
impl Media {
|
|
|
|
pub async fn parse(data: &Value) -> (String, Self, Vec<GalleryMedia>) {
|
|
|
|
let mut gallery = Vec::new();
|
|
|
|
|
|
|
|
// If post is a video, return the video
|
|
|
|
let (post_type, url) = if data["preview"]["reddit_video_preview"]["fallback_url"].is_string() {
|
|
|
|
// Return reddit video
|
|
|
|
("video", &data["preview"]["reddit_video_preview"]["fallback_url"])
|
|
|
|
} else if data["secure_media"]["reddit_video"]["fallback_url"].is_string() {
|
|
|
|
// Return reddit video
|
|
|
|
("video", &data["secure_media"]["reddit_video"]["fallback_url"])
|
|
|
|
} else if data["post_hint"].as_str().unwrap_or("") == "image" {
|
|
|
|
// Handle images, whether GIFs or pics
|
|
|
|
let preview = &data["preview"]["images"][0];
|
|
|
|
let mp4 = &preview["variants"]["mp4"];
|
|
|
|
|
|
|
|
if mp4.is_object() {
|
|
|
|
// Return the mp4 if the media is a gif
|
|
|
|
("gif", &mp4["source"]["url"])
|
|
|
|
} else {
|
|
|
|
// Return the picture if the media is an image
|
|
|
|
if data["domain"] == "i.redd.it" {
|
|
|
|
("image", &data["url"])
|
|
|
|
} else {
|
|
|
|
("image", &preview["source"]["url"])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if data["is_self"].as_bool().unwrap_or_default() {
|
|
|
|
// If type is self, return permalink
|
|
|
|
("self", &data["permalink"])
|
|
|
|
} else if data["is_gallery"].as_bool().unwrap_or_default() {
|
|
|
|
// If this post contains a gallery of images
|
|
|
|
gallery = GalleryMedia::parse(&data["gallery_data"]["items"], &data["media_metadata"]);
|
|
|
|
|
|
|
|
("gallery", &data["url"])
|
|
|
|
} else {
|
|
|
|
// If type can't be determined, return url
|
|
|
|
("link", &data["url"])
|
|
|
|
};
|
|
|
|
|
|
|
|
let source = &data["preview"]["images"][0]["source"];
|
|
|
|
|
|
|
|
(
|
|
|
|
post_type.to_string(),
|
|
|
|
Self {
|
|
|
|
url: url.as_str().unwrap_or_default().to_string(),
|
|
|
|
width: source["width"].as_i64().unwrap_or_default(),
|
|
|
|
height: source["height"].as_i64().unwrap_or_default(),
|
|
|
|
poster: format_url(source["url"].as_str().unwrap_or_default()),
|
|
|
|
},
|
|
|
|
gallery,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-07 09:05:11 +13:00
|
|
|
pub struct GalleryMedia {
|
|
|
|
pub url: String,
|
|
|
|
pub width: i64,
|
|
|
|
pub height: i64,
|
|
|
|
pub caption: String,
|
2021-02-08 14:33:54 +13:00
|
|
|
pub outbound_url: String,
|
2021-02-07 09:05:11 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
impl GalleryMedia {
|
|
|
|
fn parse(items: &Value, metadata: &Value) -> Vec<Self> {
|
2021-02-26 06:07:45 +13:00
|
|
|
items
|
|
|
|
.as_array()
|
2021-02-25 18:29:23 +13:00
|
|
|
.unwrap_or(&Vec::new())
|
|
|
|
.iter()
|
|
|
|
.map(|item| {
|
|
|
|
// For each image in gallery
|
|
|
|
let media_id = item["media_id"].as_str().unwrap_or_default();
|
|
|
|
let image = &metadata[media_id]["s"];
|
|
|
|
|
|
|
|
// Construct gallery items
|
|
|
|
Self {
|
|
|
|
url: format_url(image["u"].as_str().unwrap_or_default()),
|
|
|
|
width: image["x"].as_i64().unwrap_or_default(),
|
|
|
|
height: image["y"].as_i64().unwrap_or_default(),
|
|
|
|
caption: item["caption"].as_str().unwrap_or_default().to_string(),
|
|
|
|
outbound_url: item["outbound_url"].as_str().unwrap_or_default().to_string(),
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect::<Vec<Self>>()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-18 08:37:40 +13:00
|
|
|
// Post containing content, metadata and media
|
|
|
|
pub struct Post {
|
2021-01-04 10:06:49 +13:00
|
|
|
pub id: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub title: String,
|
|
|
|
pub community: String,
|
|
|
|
pub body: String,
|
2021-01-17 12:02:24 +13:00
|
|
|
pub author: Author,
|
2021-01-04 10:06:49 +13:00
|
|
|
pub permalink: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub score: String,
|
2021-01-04 10:06:49 +13:00
|
|
|
pub upvote_ratio: i64,
|
2020-12-01 17:33:55 +13:00
|
|
|
pub post_type: String,
|
2020-12-23 15:29:43 +13:00
|
|
|
pub flair: Flair,
|
2020-12-30 16:01:02 +13:00
|
|
|
pub flags: Flags,
|
2021-01-18 09:58:12 +13:00
|
|
|
pub thumbnail: Media,
|
|
|
|
pub media: Media,
|
2021-01-12 11:08:12 +13:00
|
|
|
pub domain: String,
|
2021-01-17 08:40:32 +13:00
|
|
|
pub rel_time: String,
|
|
|
|
pub created: String,
|
2021-01-18 08:39:57 +13:00
|
|
|
pub comments: String,
|
2021-02-07 09:05:11 +13:00
|
|
|
pub gallery: Vec<GalleryMedia>,
|
2020-11-18 08:37:40 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
impl Post {
|
|
|
|
// Fetch posts of a user or subreddit and return a vector of posts and the "after" value
|
|
|
|
pub async fn fetch(path: &str, fallback_title: String) -> Result<(Vec<Self>, String), String> {
|
|
|
|
let res;
|
|
|
|
let post_list;
|
|
|
|
|
|
|
|
// Send a request to the url
|
|
|
|
match request(path.to_string()).await {
|
|
|
|
// If success, receive JSON in response
|
|
|
|
Ok(response) => {
|
|
|
|
res = response;
|
|
|
|
}
|
|
|
|
// If the Reddit API returns an error, exit this function
|
|
|
|
Err(msg) => return Err(msg),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch the list of posts from the JSON response
|
|
|
|
match res["data"]["children"].as_array() {
|
|
|
|
Some(list) => post_list = list,
|
|
|
|
None => return Err("No posts found".to_string()),
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut posts: Vec<Self> = Vec::new();
|
|
|
|
|
|
|
|
// For each post from posts list
|
|
|
|
for post in post_list {
|
|
|
|
let data = &post["data"];
|
|
|
|
|
|
|
|
let (rel_time, created) = time(data["created_utc"].as_f64().unwrap_or_default());
|
|
|
|
let score = data["score"].as_i64().unwrap_or_default();
|
|
|
|
let ratio: f64 = data["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0;
|
|
|
|
let title = val(post, "title");
|
|
|
|
|
|
|
|
// Determine the type of media along with the media URL
|
|
|
|
let (post_type, media, gallery) = Media::parse(&data).await;
|
|
|
|
|
|
|
|
posts.push(Self {
|
|
|
|
id: val(post, "id"),
|
|
|
|
title: if title.is_empty() { fallback_title.to_owned() } else { title },
|
|
|
|
community: val(post, "subreddit"),
|
|
|
|
body: rewrite_urls(&val(post, "body_html")),
|
|
|
|
author: Author {
|
|
|
|
name: val(post, "author"),
|
|
|
|
flair: Flair {
|
|
|
|
flair_parts: FlairPart::parse(
|
|
|
|
data["author_flair_type"].as_str().unwrap_or_default(),
|
|
|
|
data["author_flair_richtext"].as_array(),
|
|
|
|
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"),
|
|
|
|
},
|
|
|
|
score: if data["hide_score"].as_bool().unwrap_or_default() {
|
|
|
|
"•".to_string()
|
|
|
|
} else {
|
|
|
|
format_num(score)
|
|
|
|
},
|
|
|
|
upvote_ratio: ratio as i64,
|
|
|
|
post_type,
|
|
|
|
thumbnail: Media {
|
|
|
|
url: format_url(val(post, "thumbnail").as_str()),
|
|
|
|
width: data["thumbnail_width"].as_i64().unwrap_or_default(),
|
|
|
|
height: data["thumbnail_height"].as_i64().unwrap_or_default(),
|
|
|
|
poster: "".to_string(),
|
|
|
|
},
|
|
|
|
media,
|
|
|
|
domain: val(post, "domain"),
|
|
|
|
flair: Flair {
|
|
|
|
flair_parts: FlairPart::parse(
|
|
|
|
data["link_flair_type"].as_str().unwrap_or_default(),
|
|
|
|
data["link_flair_richtext"].as_array(),
|
|
|
|
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 {
|
|
|
|
nsfw: data["over_18"].as_bool().unwrap_or_default(),
|
|
|
|
stickied: data["stickied"].as_bool().unwrap_or_default(),
|
|
|
|
},
|
|
|
|
permalink: val(post, "permalink"),
|
|
|
|
rel_time,
|
|
|
|
created,
|
|
|
|
comments: format_num(data["num_comments"].as_i64().unwrap_or_default()),
|
|
|
|
gallery,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok((posts, res["data"]["after"].as_str().unwrap_or_default().to_string()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-11 07:48:51 +13:00
|
|
|
#[derive(Template)]
|
|
|
|
#[template(path = "comment.html", escape = "none")]
|
2020-11-18 08:37:40 +13:00
|
|
|
// Comment with content, post, score and data/time that it was posted
|
|
|
|
pub struct Comment {
|
2020-12-21 17:52:15 +13:00
|
|
|
pub id: String,
|
2021-02-11 07:48:51 +13:00
|
|
|
pub kind: String,
|
2021-02-13 06:16:59 +13:00
|
|
|
pub parent_id: String,
|
|
|
|
pub parent_kind: String,
|
2021-02-11 07:48:51 +13:00
|
|
|
pub post_link: String,
|
|
|
|
pub post_author: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub body: String,
|
2021-01-17 12:02:24 +13:00
|
|
|
pub author: Author,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub score: String,
|
2021-01-17 08:40:32 +13:00
|
|
|
pub rel_time: String,
|
|
|
|
pub created: String,
|
2021-02-15 11:53:09 +13:00
|
|
|
pub edited: (String, String),
|
2020-12-20 16:54:46 +13:00
|
|
|
pub replies: Vec<Comment>,
|
2021-02-13 06:16:59 +13:00
|
|
|
pub highlighted: bool,
|
2020-11-18 08:37:40 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
#[derive(Template)]
|
|
|
|
#[template(path = "error.html", escape = "none")]
|
|
|
|
pub struct ErrorTemplate {
|
|
|
|
pub msg: String,
|
|
|
|
pub prefs: Preferences,
|
|
|
|
}
|
|
|
|
|
2021-01-09 17:55:40 +13:00
|
|
|
#[derive(Default)]
|
2020-11-18 08:37:40 +13:00
|
|
|
// User struct containing metadata about user
|
|
|
|
pub struct User {
|
|
|
|
pub name: String,
|
2021-01-01 17:21:56 +13:00
|
|
|
pub title: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub icon: String,
|
|
|
|
pub karma: i64,
|
2020-12-24 19:16:04 +13:00
|
|
|
pub created: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub banner: String,
|
2020-11-30 15:50:29 +13:00
|
|
|
pub description: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
}
|
|
|
|
|
2020-12-29 15:42:46 +13:00
|
|
|
#[derive(Default)]
|
2020-11-18 08:37:40 +13:00
|
|
|
// Subreddit struct containing metadata about community
|
|
|
|
pub struct Subreddit {
|
|
|
|
pub name: String,
|
|
|
|
pub title: String,
|
|
|
|
pub description: String,
|
2020-12-29 15:42:46 +13:00
|
|
|
pub info: String,
|
2020-11-18 08:37:40 +13:00
|
|
|
pub icon: String,
|
2020-11-23 13:43:23 +13:00
|
|
|
pub members: String,
|
2020-11-30 15:50:29 +13:00
|
|
|
pub active: String,
|
2021-01-02 19:21:43 +13:00
|
|
|
pub wiki: bool,
|
2020-11-18 08:37:40 +13:00
|
|
|
}
|
|
|
|
|
2020-11-20 10:49:32 +13:00
|
|
|
// Parser for query params, used in sorting (eg. /r/rust/?sort=hot)
|
|
|
|
#[derive(serde::Deserialize)]
|
|
|
|
pub struct Params {
|
2020-12-30 14:11:47 +13:00
|
|
|
pub t: Option<String>,
|
2021-01-01 12:54:13 +13:00
|
|
|
pub q: Option<String>,
|
2020-11-20 10:49:32 +13:00
|
|
|
pub sort: Option<String>,
|
|
|
|
pub after: Option<String>,
|
2020-11-30 15:50:29 +13:00
|
|
|
pub before: Option<String>,
|
2020-11-20 10:49:32 +13:00
|
|
|
}
|
|
|
|
|
2021-01-11 15:15:34 +13:00
|
|
|
#[derive(Default)]
|
2021-01-09 14:35:04 +13:00
|
|
|
pub struct Preferences {
|
2021-01-11 15:15:34 +13:00
|
|
|
pub theme: String,
|
2021-01-09 17:55:40 +13:00
|
|
|
pub front_page: String,
|
2021-01-09 14:35:04 +13:00
|
|
|
pub layout: String,
|
2021-01-11 10:08:36 +13:00
|
|
|
pub wide: String,
|
2021-01-31 18:43:46 +13:00
|
|
|
pub show_nsfw: String,
|
2021-01-09 14:50:03 +13:00
|
|
|
pub comment_sort: String,
|
2021-02-14 09:55:23 +13:00
|
|
|
pub subscriptions: Vec<String>,
|
2021-01-09 14:35:04 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
impl Preferences {
|
|
|
|
// Build preferences from cookies
|
|
|
|
pub fn new(req: Request<()>) -> Self {
|
|
|
|
Self {
|
|
|
|
theme: cookie(&req, "theme"),
|
|
|
|
front_page: cookie(&req, "front_page"),
|
|
|
|
layout: cookie(&req, "layout"),
|
|
|
|
wide: cookie(&req, "wide"),
|
|
|
|
show_nsfw: cookie(&req, "show_nsfw"),
|
|
|
|
comment_sort: cookie(&req, "comment_sort"),
|
|
|
|
subscriptions: cookie(&req, "subscriptions").split('+').map(String::from).filter(|s| !s.is_empty()).collect(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 18:10:08 +13:00
|
|
|
//
|
2020-12-08 07:53:22 +13:00
|
|
|
// FORMATTING
|
2020-12-01 18:10:08 +13:00
|
|
|
//
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
// Grab a query parameter from a url
|
2021-01-02 09:33:57 +13:00
|
|
|
pub fn param(path: &str, value: &str) -> String {
|
2021-01-15 11:56:28 +13:00
|
|
|
match Url::parse(format!("https://libredd.it/{}", path).as_str()) {
|
2021-02-14 12:02:38 +13:00
|
|
|
Ok(url) => url.query_pairs().into_owned().collect::<HashMap<_, _>>().get(value).unwrap_or(&String::new()).to_owned(),
|
2021-01-15 11:56:28 +13:00
|
|
|
_ => String::new(),
|
|
|
|
}
|
2021-01-01 12:54:13 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
// Parse a cookie value from request
|
2021-02-10 06:38:52 +13:00
|
|
|
pub fn cookie(req: &Request<()>, name: &str) -> String {
|
|
|
|
let cookie = req.cookie(name).unwrap_or_else(|| Cookie::named(name));
|
|
|
|
cookie.value().to_string()
|
2021-01-06 15:04:49 +13:00
|
|
|
}
|
2021-01-03 17:50:23 +13:00
|
|
|
|
2020-12-26 15:06:33 +13:00
|
|
|
// Direct urls to proxy if proxy is enabled
|
2021-01-12 14:47:14 +13:00
|
|
|
pub fn format_url(url: &str) -> String {
|
2021-01-09 14:35:04 +13:00
|
|
|
if url.is_empty() || url == "self" || url == "default" || url == "nsfw" || url == "spoiler" {
|
2021-01-05 16:26:41 +13:00
|
|
|
String::new()
|
|
|
|
} else {
|
2021-02-20 18:46:44 +13:00
|
|
|
match Url::parse(url) {
|
|
|
|
Ok(parsed) => {
|
|
|
|
let domain = parsed.domain().unwrap_or_default();
|
|
|
|
|
|
|
|
let capture = |regex: &str, format: &str, levels: i16| {
|
|
|
|
Regex::new(regex)
|
|
|
|
.map(|re| match re.captures(url) {
|
|
|
|
Some(caps) => match levels {
|
|
|
|
1 => [format, &caps[1], "/"].join(""),
|
|
|
|
2 => [format, &caps[1], "/", &caps[2], "/"].join(""),
|
|
|
|
_ => String::new(),
|
|
|
|
},
|
|
|
|
None => String::new(),
|
|
|
|
})
|
|
|
|
.unwrap_or_default()
|
|
|
|
};
|
|
|
|
|
|
|
|
match domain {
|
|
|
|
"v.redd.it" => capture(r"https://v\.redd\.it/(.*)/DASH_([0-9]{2,4}(\.mp4|$))", "/vid/", 2),
|
|
|
|
"i.redd.it" => capture(r"https://i\.redd\.it/(.*)", "/img/", 1),
|
|
|
|
"a.thumbs.redditmedia.com" => capture(r"https://a\.thumbs\.redditmedia\.com/(.*)", "/thumb/a/", 1),
|
|
|
|
"b.thumbs.redditmedia.com" => capture(r"https://b\.thumbs\.redditmedia\.com/(.*)", "/thumb/b/", 1),
|
|
|
|
"emoji.redditmedia.com" => capture(r"https://emoji\.redditmedia\.com/(.*)/(.*)", "/emoji/", 2),
|
2021-02-20 18:49:02 +13:00
|
|
|
"preview.redd.it" => capture(r"https://preview\.redd\.it/(.*)\?(.*)", "/preview/pre/", 2),
|
|
|
|
"external-preview.redd.it" => capture(r"https://external\-preview\.redd\.it/(.*)\?(.*)", "/preview/external-pre/", 2),
|
2021-02-20 18:46:44 +13:00
|
|
|
"styles.redditmedia.com" => capture(r"https://styles\.redditmedia\.com/(.*)", "/style/", 1),
|
|
|
|
"www.redditstatic.com" => capture(r"https://www\.redditstatic\.com/(.*)", "/static/", 1),
|
|
|
|
_ => String::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(_) => String::new(),
|
2021-02-19 07:04:59 +13:00
|
|
|
}
|
2021-01-05 16:26:41 +13:00
|
|
|
}
|
2020-12-01 18:10:08 +13:00
|
|
|
}
|
|
|
|
|
2021-01-03 07:58:21 +13:00
|
|
|
// Rewrite Reddit links to Libreddit in body of text
|
2021-02-10 18:56:38 +13:00
|
|
|
pub fn rewrite_urls(text: &str) -> String {
|
2021-02-21 09:14:32 +13:00
|
|
|
match Regex::new(r#"href="(https|http|)://(www.|old.|np.|)(reddit).(com)/"#) {
|
|
|
|
Ok(re) => re.replace_all(text, r#"href="/"#).to_string(),
|
|
|
|
Err(_) => String::new(),
|
|
|
|
}
|
2021-01-03 07:58:21 +13:00
|
|
|
}
|
|
|
|
|
2020-12-26 15:06:33 +13:00
|
|
|
// Append `m` and `k` for millions and thousands respectively
|
2020-12-08 07:53:22 +13:00
|
|
|
pub fn format_num(num: i64) -> String {
|
2021-01-18 09:59:40 +13:00
|
|
|
if num >= 1_000_000 {
|
2021-01-09 14:35:04 +13:00
|
|
|
format!("{}m", num / 1_000_000)
|
2021-01-18 09:59:40 +13:00
|
|
|
} else if num >= 1000 {
|
2021-01-09 14:35:04 +13:00
|
|
|
format!("{}k", num / 1_000)
|
2020-12-08 08:36:05 +13:00
|
|
|
} else {
|
|
|
|
num.to_string()
|
|
|
|
}
|
2020-12-08 07:53:22 +13:00
|
|
|
}
|
|
|
|
|
2021-02-25 18:29:23 +13:00
|
|
|
// Parse a relative and absolute time from a UNIX timestamp
|
2021-01-17 08:40:32 +13:00
|
|
|
pub fn time(created: f64) -> (String, String) {
|
|
|
|
let time = OffsetDateTime::from_unix_timestamp(created.round() as i64);
|
2021-01-13 07:59:32 +13:00
|
|
|
let time_delta = OffsetDateTime::now_utc() - time;
|
2021-01-17 08:40:32 +13:00
|
|
|
|
2021-01-15 12:13:52 +13:00
|
|
|
// If the time difference is more than a month, show full date
|
2021-01-17 08:40:32 +13:00
|
|
|
let rel_time = if time_delta > Duration::days(30) {
|
2021-01-15 12:13:52 +13:00
|
|
|
time.format("%b %d '%y")
|
|
|
|
// Otherwise, show relative date/time
|
2021-01-14 13:31:24 +13:00
|
|
|
} else if time_delta.whole_days() > 0 {
|
|
|
|
format!("{}d ago", time_delta.whole_days())
|
2021-01-13 07:59:32 +13:00
|
|
|
} else if time_delta.whole_hours() > 0 {
|
|
|
|
format!("{}h ago", time_delta.whole_hours())
|
|
|
|
} else {
|
|
|
|
format!("{}m ago", time_delta.whole_minutes())
|
2021-01-17 08:40:32 +13:00
|
|
|
};
|
|
|
|
|
2021-02-15 11:53:09 +13:00
|
|
|
(rel_time, time.format("%b %d %Y, %H:%M:%S UTC"))
|
2021-01-13 07:59:32 +13:00
|
|
|
}
|
|
|
|
|
2020-11-20 17:42:18 +13:00
|
|
|
//
|
|
|
|
// JSON PARSING
|
|
|
|
//
|
|
|
|
|
2020-11-18 08:37:40 +13:00
|
|
|
// val() function used to parse JSON from Reddit APIs
|
2021-01-15 06:53:54 +13:00
|
|
|
pub fn val(j: &Value, k: &str) -> String {
|
2021-01-22 18:25:51 +13:00
|
|
|
j["data"][k].as_str().unwrap_or_default().to_string()
|
2020-11-18 08:37:40 +13:00
|
|
|
}
|
|
|
|
|
2020-11-20 17:42:18 +13:00
|
|
|
//
|
|
|
|
// NETWORKING
|
|
|
|
//
|
|
|
|
|
2021-02-14 12:02:38 +13:00
|
|
|
pub fn template(t: impl Template) -> tide::Result {
|
|
|
|
Ok(Response::builder(200).content_type("text/html").body(t.render().unwrap_or_default()).build())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn redirect(path: String) -> Response {
|
|
|
|
Response::builder(302)
|
|
|
|
.content_type("text/html")
|
|
|
|
.header("Location", &path)
|
|
|
|
.body(format!("Redirecting to <a href=\"{0}\">{0}</a>...", path))
|
|
|
|
.build()
|
2021-02-10 06:38:52 +13:00
|
|
|
}
|
|
|
|
|
2021-02-21 15:36:30 +13:00
|
|
|
pub async fn error(req: Request<()>, msg: String) -> tide::Result {
|
2021-02-26 06:07:45 +13:00
|
|
|
let body = ErrorTemplate {
|
|
|
|
msg,
|
|
|
|
prefs: Preferences::new(req),
|
|
|
|
}
|
|
|
|
.render()
|
|
|
|
.unwrap_or_default();
|
2021-02-10 06:38:52 +13:00
|
|
|
|
|
|
|
Ok(Response::builder(404).content_type("text/html").body(body).build())
|
2021-01-01 18:03:44 +13:00
|
|
|
}
|
|
|
|
|
2020-11-19 15:50:59 +13:00
|
|
|
// Make a request to a Reddit API and parse the JSON response
|
2021-02-08 14:56:06 +13:00
|
|
|
#[cached(size = 100, time = 30, result = true)]
|
2021-01-23 22:48:33 +13:00
|
|
|
pub async fn request(path: String) -> Result<Value, String> {
|
2021-01-12 07:33:48 +13:00
|
|
|
let url = format!("https://www.reddit.com{}", path);
|
2021-02-10 06:38:52 +13:00
|
|
|
// Build reddit-compliant user agent for Libreddit
|
2021-01-17 12:13:34 +13:00
|
|
|
let user_agent = format!("web:libreddit:{}", env!("CARGO_PKG_VERSION"));
|
2021-01-12 07:33:48 +13:00
|
|
|
|
2021-02-10 06:38:52 +13:00
|
|
|
// Send request using surf
|
|
|
|
let req = surf::get(&url).header("User-Agent", user_agent.as_str());
|
|
|
|
let client = surf::client().with(surf::middleware::Redirect::new(5));
|
|
|
|
|
|
|
|
let res = client.send(req).await;
|
|
|
|
|
2021-02-23 13:43:32 +13:00
|
|
|
let err = |msg: &str, e: String| -> Result<Value, String> {
|
|
|
|
println!("{} - {}: {}", url, msg, e);
|
|
|
|
Err(msg.to_string())
|
|
|
|
};
|
|
|
|
|
2021-02-20 18:46:44 +13:00
|
|
|
match res {
|
|
|
|
Ok(mut response) => match response.take_body().into_string().await {
|
|
|
|
// If response is success
|
|
|
|
Ok(body) => {
|
|
|
|
// Parse the response from Reddit as JSON
|
2021-02-23 13:43:32 +13:00
|
|
|
let parsed: Result<Value, Error> = from_str(&body);
|
|
|
|
match parsed {
|
|
|
|
Ok(json) => {
|
|
|
|
// If Reddit returned an error
|
|
|
|
if json["error"].is_i64() {
|
|
|
|
Err(
|
|
|
|
json["reason"]
|
|
|
|
.as_str()
|
2021-02-25 18:29:23 +13:00
|
|
|
.unwrap_or(json["message"].as_str().unwrap_or_else(|| {
|
|
|
|
println!("{} - Error parsing reddit error", url);
|
|
|
|
"Error parsing reddit error"
|
|
|
|
}))
|
2021-02-23 13:43:32 +13:00
|
|
|
.to_string(),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
Ok(json)
|
|
|
|
}
|
2021-02-20 18:46:44 +13:00
|
|
|
}
|
2021-02-23 13:43:32 +13:00
|
|
|
Err(e) => err("Failed to parse page JSON data", e.to_string()),
|
2021-01-16 18:26:51 +13:00
|
|
|
}
|
|
|
|
}
|
2021-02-23 13:43:32 +13:00
|
|
|
Err(e) => err("Couldn't parse request body", e.to_string()),
|
2021-02-20 18:46:44 +13:00
|
|
|
},
|
2021-02-23 13:43:32 +13:00
|
|
|
Err(e) => err("Couldn't send request to Reddit", e.to_string()),
|
2021-01-16 18:26:51 +13:00
|
|
|
}
|
2020-11-19 15:50:59 +13:00
|
|
|
}
|