use crate::esc;
use crate::utils::{error, format_url, param, request, template, Post, Preferences, User};
use askama::Template;
use tide::Request;
use time::OffsetDateTime;
#[derive(Template)]
#[template(path = "user.html", escape = "none")]
struct UserTemplate {
user: User,
posts: Vec<Post>,
sort: (String, String),
ends: (String, String),
prefs: Preferences,
}
pub async fn profile(req: Request<()>) -> tide::Result {
let path = format!("{}.json?{}&raw_json=1", req.url().path(), req.url().query().unwrap_or_default());
let sort = param(&path, "sort");
let username = req.param("name").unwrap_or("").to_string();
let posts = Post::fetch(&path, "Comment".to_string()).await;
match posts {
Ok((posts, after)) => {
let user = user(&username).await.unwrap_or_default();
template(UserTemplate {
user,
posts,
sort: (sort, param(&path, "t")),
ends: (param(&path, "after"), after),
prefs: Preferences::new(req),
})
}
Err(msg) => error(req, msg).await,
}
}
async fn user(name: &str) -> Result<User, String> {
let path: String = format!("/user/{}/about.json?raw_json=1", name);
match request(path).await {
Ok(res) => {
let created: i64 = res["data"]["created"].as_f64().unwrap_or(0.0).round() as i64;
let about = |item| res["data"]["subreddit"][item].as_str().unwrap_or_default().to_string();
Ok(User {
name: name.to_string(),
title: esc!(about("title")),
icon: format_url(&about("icon_img")),
karma: res["data"]["total_karma"].as_i64().unwrap_or(0),
created: OffsetDateTime::from_unix_timestamp(created).format("%b %d '%y"),
banner: esc!(about("banner_img")),
description: about("public_description"),
})
}
Err(msg) => return Err(msg),
}
}