You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

446 lines
15KB

  1. use std::collections::HashMap;
  2. use std::path::PathBuf;
  3. use std::sync::{Arc, Mutex, RwLock};
  4. use tera::{from_value, to_value, Function as TeraFn, Result, Value};
  5. use config::Config;
  6. use library::{Library, Taxonomy};
  7. use utils::site::resolve_internal_link;
  8. use imageproc;
  9. #[macro_use]
  10. mod macros;
  11. mod load_data;
  12. pub use self::load_data::LoadData;
  13. #[derive(Debug)]
  14. pub struct Trans {
  15. config: Config,
  16. }
  17. impl Trans {
  18. pub fn new(config: Config) -> Self {
  19. Self { config }
  20. }
  21. }
  22. impl TeraFn for Trans {
  23. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  24. let key = required_arg!(String, args.get("key"), "`trans` requires a `key` argument.");
  25. let lang = optional_arg!(String, args.get("lang"), "`trans`: `lang` must be a string.")
  26. .unwrap_or_else(|| self.config.default_language.clone());
  27. let translations = &self.config.translations[lang.as_str()];
  28. Ok(to_value(&translations[key.as_str()]).unwrap())
  29. }
  30. }
  31. #[derive(Debug)]
  32. pub struct GetUrl {
  33. config: Config,
  34. permalinks: HashMap<String, String>,
  35. }
  36. impl GetUrl {
  37. pub fn new(config: Config, permalinks: HashMap<String, String>) -> Self {
  38. Self { config, permalinks }
  39. }
  40. }
  41. impl TeraFn for GetUrl {
  42. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  43. let cachebust =
  44. args.get("cachebust").map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  45. let trailing_slash = args
  46. .get("trailing_slash")
  47. .map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  48. let path = required_arg!(
  49. String,
  50. args.get("path"),
  51. "`get_url` requires a `path` argument with a string value"
  52. );
  53. if path.starts_with("./") {
  54. match resolve_internal_link(&path, &self.permalinks) {
  55. Ok(url) => Ok(to_value(url).unwrap()),
  56. Err(_) => {
  57. Err(format!("Could not resolve URL for link `{}` not found.", path).into())
  58. }
  59. }
  60. } else {
  61. // anything else
  62. let mut permalink = self.config.make_permalink(&path);
  63. if !trailing_slash && permalink.ends_with('/') {
  64. permalink.pop(); // Removes the slash
  65. }
  66. if cachebust {
  67. permalink = format!("{}?t={}", permalink, self.config.build_timestamp.unwrap());
  68. }
  69. Ok(to_value(permalink).unwrap())
  70. }
  71. }
  72. }
  73. #[derive(Debug)]
  74. pub struct ResizeImage {
  75. imageproc: Arc<Mutex<imageproc::Processor>>,
  76. }
  77. impl ResizeImage {
  78. pub fn new(imageproc: Arc<Mutex<imageproc::Processor>>) -> Self {
  79. Self { imageproc }
  80. }
  81. }
  82. static DEFAULT_OP: &'static str = "fill";
  83. static DEFAULT_FMT: &'static str = "auto";
  84. const DEFAULT_Q: u8 = 75;
  85. impl TeraFn for ResizeImage {
  86. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  87. let path = required_arg!(
  88. String,
  89. args.get("path"),
  90. "`resize_image` requires a `path` argument with a string value"
  91. );
  92. let width = optional_arg!(
  93. u32,
  94. args.get("width"),
  95. "`resize_image`: `width` must be a non-negative integer"
  96. );
  97. let height = optional_arg!(
  98. u32,
  99. args.get("height"),
  100. "`resize_image`: `height` must be a non-negative integer"
  101. );
  102. let op = optional_arg!(String, args.get("op"), "`resize_image`: `op` must be a string")
  103. .unwrap_or_else(|| DEFAULT_OP.to_string());
  104. let format =
  105. optional_arg!(String, args.get("format"), "`resize_image`: `format` must be a string")
  106. .unwrap_or_else(|| DEFAULT_FMT.to_string());
  107. let quality =
  108. optional_arg!(u8, args.get("quality"), "`resize_image`: `quality` must be a number")
  109. .unwrap_or(DEFAULT_Q);
  110. if quality == 0 || quality > 100 {
  111. return Err("`resize_image`: `quality` must be in range 1-100".to_string().into());
  112. }
  113. let mut imageproc = self.imageproc.lock().unwrap();
  114. if !imageproc.source_exists(&path) {
  115. return Err(format!("`resize_image`: Cannot find path: {}", path).into());
  116. }
  117. let imageop = imageproc::ImageOp::from_args(path, &op, width, height, &format, quality)
  118. .map_err(|e| format!("`resize_image`: {}", e))?;
  119. let url = imageproc.insert(imageop);
  120. to_value(url).map_err(|err| err.into())
  121. }
  122. }
  123. #[derive(Debug)]
  124. pub struct GetTaxonomyUrl {
  125. taxonomies: HashMap<String, HashMap<String, String>>,
  126. }
  127. impl GetTaxonomyUrl {
  128. pub fn new(all_taxonomies: &[Taxonomy]) -> Self {
  129. let mut taxonomies = HashMap::new();
  130. for taxonomy in all_taxonomies {
  131. let mut items = HashMap::new();
  132. for item in &taxonomy.items {
  133. items.insert(item.name.clone(), item.permalink.clone());
  134. }
  135. taxonomies.insert(taxonomy.kind.name.clone(), items);
  136. }
  137. Self { taxonomies }
  138. }
  139. }
  140. impl TeraFn for GetTaxonomyUrl {
  141. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  142. let kind = required_arg!(
  143. String,
  144. args.get("kind"),
  145. "`get_taxonomy_url` requires a `kind` argument with a string value"
  146. );
  147. let name = required_arg!(
  148. String,
  149. args.get("name"),
  150. "`get_taxonomy_url` requires a `name` argument with a string value"
  151. );
  152. let container = match self.taxonomies.get(&kind) {
  153. Some(c) => c,
  154. None => {
  155. return Err(format!(
  156. "`get_taxonomy_url` received an unknown taxonomy as kind: {}",
  157. kind
  158. )
  159. .into());
  160. }
  161. };
  162. if let Some(permalink) = container.get(&name) {
  163. return Ok(to_value(permalink).unwrap());
  164. }
  165. Err(format!("`get_taxonomy_url`: couldn't find `{}` in `{}` taxonomy", name, kind).into())
  166. }
  167. }
  168. #[derive(Debug)]
  169. pub struct GetPage {
  170. base_path: PathBuf,
  171. library: Arc<RwLock<Library>>,
  172. }
  173. impl GetPage {
  174. pub fn new(base_path: PathBuf, library: Arc<RwLock<Library>>) -> Self {
  175. Self { base_path: base_path.join("content"), library }
  176. }
  177. }
  178. impl TeraFn for GetPage {
  179. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  180. let path = required_arg!(
  181. String,
  182. args.get("path"),
  183. "`get_page` requires a `path` argument with a string value"
  184. );
  185. let full_path = self.base_path.join(&path);
  186. let library = self.library.read().unwrap();
  187. match library.get_page(&full_path) {
  188. Some(p) => Ok(to_value(p.to_serialized(&library)).unwrap()),
  189. None => Err(format!("Page `{}` not found.", path).into()),
  190. }
  191. }
  192. }
  193. #[derive(Debug)]
  194. pub struct GetSection {
  195. base_path: PathBuf,
  196. library: Arc<RwLock<Library>>,
  197. }
  198. impl GetSection {
  199. pub fn new(base_path: PathBuf, library: Arc<RwLock<Library>>) -> Self {
  200. Self { base_path: base_path.join("content"), library }
  201. }
  202. }
  203. impl TeraFn for GetSection {
  204. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  205. let path = required_arg!(
  206. String,
  207. args.get("path"),
  208. "`get_section` requires a `path` argument with a string value"
  209. );
  210. let metadata_only = args
  211. .get("metadata_only")
  212. .map_or(false, |c| from_value::<bool>(c.clone()).unwrap_or(false));
  213. let full_path = self.base_path.join(&path);
  214. let library = self.library.read().unwrap();
  215. match library.get_section(&full_path) {
  216. Some(s) => {
  217. if metadata_only {
  218. Ok(to_value(s.to_serialized_basic(&library)).unwrap())
  219. } else {
  220. Ok(to_value(s.to_serialized(&library)).unwrap())
  221. }
  222. }
  223. None => Err(format!("Section `{}` not found.", path).into()),
  224. }
  225. }
  226. }
  227. #[derive(Debug)]
  228. pub struct GetTaxonomy {
  229. library: Arc<RwLock<Library>>,
  230. taxonomies: HashMap<String, Taxonomy>,
  231. }
  232. impl GetTaxonomy {
  233. pub fn new(all_taxonomies: Vec<Taxonomy>, library: Arc<RwLock<Library>>) -> Self {
  234. let mut taxonomies = HashMap::new();
  235. for taxo in all_taxonomies {
  236. taxonomies.insert(taxo.kind.name.clone(), taxo);
  237. }
  238. Self { taxonomies, library }
  239. }
  240. }
  241. impl TeraFn for GetTaxonomy {
  242. fn call(&self, args: &HashMap<String, Value>) -> Result<Value> {
  243. let kind = required_arg!(
  244. String,
  245. args.get("kind"),
  246. "`get_taxonomy` requires a `kind` argument with a string value"
  247. );
  248. match self.taxonomies.get(&kind) {
  249. Some(t) => Ok(to_value(t.to_serialized(&self.library.read().unwrap())).unwrap()),
  250. None => {
  251. Err(format!("`get_taxonomy` received an unknown taxonomy as kind: {}", kind).into())
  252. }
  253. }
  254. }
  255. }
  256. #[cfg(test)]
  257. mod tests {
  258. use super::{GetTaxonomy, GetTaxonomyUrl, GetUrl, Trans};
  259. use std::collections::HashMap;
  260. use std::sync::{Arc, RwLock};
  261. use tera::{to_value, Function, Value};
  262. use config::{Config, Taxonomy as TaxonomyConfig};
  263. use library::{Library, Taxonomy, TaxonomyItem};
  264. #[test]
  265. fn can_add_cachebust_to_url() {
  266. let config = Config::default();
  267. let static_fn = GetUrl::new(config, HashMap::new());
  268. let mut args = HashMap::new();
  269. args.insert("path".to_string(), to_value("app.css").unwrap());
  270. args.insert("cachebust".to_string(), to_value(true).unwrap());
  271. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css?t=1");
  272. }
  273. #[test]
  274. fn can_add_trailing_slashes() {
  275. let config = Config::default();
  276. let static_fn = GetUrl::new(config, HashMap::new());
  277. let mut args = HashMap::new();
  278. args.insert("path".to_string(), to_value("app.css").unwrap());
  279. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  280. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css/");
  281. }
  282. #[test]
  283. fn can_add_slashes_and_cachebust() {
  284. let config = Config::default();
  285. let static_fn = GetUrl::new(config, HashMap::new());
  286. let mut args = HashMap::new();
  287. args.insert("path".to_string(), to_value("app.css").unwrap());
  288. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  289. args.insert("cachebust".to_string(), to_value(true).unwrap());
  290. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css/?t=1");
  291. }
  292. #[test]
  293. fn can_link_to_some_static_file() {
  294. let config = Config::default();
  295. let static_fn = GetUrl::new(config, HashMap::new());
  296. let mut args = HashMap::new();
  297. args.insert("path".to_string(), to_value("app.css").unwrap());
  298. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css");
  299. }
  300. #[test]
  301. fn can_get_taxonomy() {
  302. let config = Config::default();
  303. let taxo_config = TaxonomyConfig {
  304. name: "tags".to_string(),
  305. lang: config.default_language.clone(),
  306. ..TaxonomyConfig::default()
  307. };
  308. let library = Arc::new(RwLock::new(Library::new(0, 0, false)));
  309. let tag = TaxonomyItem::new(
  310. "Programming",
  311. &taxo_config,
  312. &config,
  313. vec![],
  314. &library.read().unwrap(),
  315. );
  316. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  317. let taxonomies = vec![tags.clone()];
  318. let static_fn = GetTaxonomy::new(taxonomies.clone(), library.clone());
  319. // can find it correctly
  320. let mut args = HashMap::new();
  321. args.insert("kind".to_string(), to_value("tags").unwrap());
  322. let res = static_fn.call(&args).unwrap();
  323. let res_obj = res.as_object().unwrap();
  324. assert_eq!(res_obj["kind"], to_value(tags.kind).unwrap());
  325. assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
  326. assert_eq!(
  327. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
  328. Value::String("Programming".to_string())
  329. );
  330. assert_eq!(
  331. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["slug"],
  332. Value::String("programming".to_string())
  333. );
  334. assert_eq!(
  335. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()
  336. ["permalink"],
  337. Value::String("http://a-website.com/tags/programming/".to_string())
  338. );
  339. assert_eq!(
  340. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["pages"],
  341. Value::Array(vec![])
  342. );
  343. // and errors if it can't find it
  344. let mut args = HashMap::new();
  345. args.insert("kind".to_string(), to_value("something-else").unwrap());
  346. assert!(static_fn.call(&args).is_err());
  347. }
  348. #[test]
  349. fn can_get_taxonomy_url() {
  350. let config = Config::default();
  351. let taxo_config = TaxonomyConfig {
  352. name: "tags".to_string(),
  353. lang: config.default_language.clone(),
  354. ..TaxonomyConfig::default()
  355. };
  356. let library = Library::new(0, 0, false);
  357. let tag = TaxonomyItem::new("Programming", &taxo_config, &config, vec![], &library);
  358. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  359. let taxonomies = vec![tags.clone()];
  360. let static_fn = GetTaxonomyUrl::new(&taxonomies);
  361. // can find it correctly
  362. let mut args = HashMap::new();
  363. args.insert("kind".to_string(), to_value("tags").unwrap());
  364. args.insert("name".to_string(), to_value("Programming").unwrap());
  365. assert_eq!(
  366. static_fn.call(&args).unwrap(),
  367. to_value("http://a-website.com/tags/programming/").unwrap()
  368. );
  369. // and errors if it can't find it
  370. let mut args = HashMap::new();
  371. args.insert("kind".to_string(), to_value("tags").unwrap());
  372. args.insert("name".to_string(), to_value("random").unwrap());
  373. assert!(static_fn.call(&args).is_err());
  374. }
  375. #[test]
  376. fn can_translate_a_string() {
  377. let trans_config = r#"
  378. base_url = "https://remplace-par-ton-url.fr"
  379. default_language = "fr"
  380. [translations]
  381. [translations.fr]
  382. title = "Un titre"
  383. [translations.en]
  384. title = "A title"
  385. "#;
  386. let config = Config::parse(trans_config).unwrap();
  387. let static_fn = Trans::new(config);
  388. let mut args = HashMap::new();
  389. args.insert("key".to_string(), to_value("title").unwrap());
  390. assert_eq!(static_fn.call(&args).unwrap(), "Un titre");
  391. args.insert("lang".to_string(), to_value("en").unwrap());
  392. assert_eq!(static_fn.call(&args).unwrap(), "A title");
  393. args.insert("lang".to_string(), to_value("fr").unwrap());
  394. assert_eq!(static_fn.call(&args).unwrap(), "Un titre");
  395. }
  396. }