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.

563 lines
19KB

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