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.

566 lines
20KB

  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_metadata` 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_metadata`: 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. use utils::slugs::SlugifyStrategy;
  310. #[test]
  311. fn can_add_cachebust_to_url() {
  312. let config = Config::default();
  313. let static_fn = GetUrl::new(config, HashMap::new());
  314. let mut args = HashMap::new();
  315. args.insert("path".to_string(), to_value("app.css").unwrap());
  316. args.insert("cachebust".to_string(), to_value(true).unwrap());
  317. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css?t=1");
  318. }
  319. #[test]
  320. fn can_add_trailing_slashes() {
  321. let config = Config::default();
  322. let static_fn = GetUrl::new(config, HashMap::new());
  323. let mut args = HashMap::new();
  324. args.insert("path".to_string(), to_value("app.css").unwrap());
  325. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  326. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css/");
  327. }
  328. #[test]
  329. fn can_add_slashes_and_cachebust() {
  330. let config = Config::default();
  331. let static_fn = GetUrl::new(config, HashMap::new());
  332. let mut args = HashMap::new();
  333. args.insert("path".to_string(), to_value("app.css").unwrap());
  334. args.insert("trailing_slash".to_string(), to_value(true).unwrap());
  335. args.insert("cachebust".to_string(), to_value(true).unwrap());
  336. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css/?t=1");
  337. }
  338. #[test]
  339. fn can_link_to_some_static_file() {
  340. let config = Config::default();
  341. let static_fn = GetUrl::new(config, HashMap::new());
  342. let mut args = HashMap::new();
  343. args.insert("path".to_string(), to_value("app.css").unwrap());
  344. assert_eq!(static_fn.call(&args).unwrap(), "http://a-website.com/app.css");
  345. }
  346. #[test]
  347. fn can_get_taxonomy() {
  348. let mut config = Config::default();
  349. config.slugify.taxonomies = SlugifyStrategy::On;
  350. let taxo_config = TaxonomyConfig {
  351. name: "tags".to_string(),
  352. lang: config.default_language.clone(),
  353. ..TaxonomyConfig::default()
  354. };
  355. let taxo_config_fr = TaxonomyConfig {
  356. name: "tags".to_string(),
  357. lang: "fr".to_string(),
  358. ..TaxonomyConfig::default()
  359. };
  360. let library = Arc::new(RwLock::new(Library::new(0, 0, false)));
  361. let tag = TaxonomyItem::new(
  362. "Programming",
  363. &taxo_config,
  364. &config,
  365. vec![],
  366. &library.read().unwrap(),
  367. );
  368. let tag_fr = TaxonomyItem::new(
  369. "Programmation",
  370. &taxo_config_fr,
  371. &config,
  372. vec![],
  373. &library.read().unwrap(),
  374. );
  375. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  376. let tags_fr = Taxonomy { kind: taxo_config_fr, items: vec![tag_fr] };
  377. let taxonomies = vec![tags.clone(), tags_fr.clone()];
  378. let static_fn =
  379. GetTaxonomy::new(&config.default_language, taxonomies.clone(), library.clone());
  380. // can find it correctly
  381. let mut args = HashMap::new();
  382. args.insert("kind".to_string(), to_value("tags").unwrap());
  383. let res = static_fn.call(&args).unwrap();
  384. let res_obj = res.as_object().unwrap();
  385. assert_eq!(res_obj["kind"], to_value(tags.kind).unwrap());
  386. assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
  387. assert_eq!(
  388. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
  389. Value::String("Programming".to_string())
  390. );
  391. assert_eq!(
  392. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["slug"],
  393. Value::String("programming".to_string())
  394. );
  395. assert_eq!(
  396. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()
  397. ["permalink"],
  398. Value::String("http://a-website.com/tags/programming/".to_string())
  399. );
  400. assert_eq!(
  401. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["pages"],
  402. Value::Array(vec![])
  403. );
  404. // Works with other languages as well
  405. let mut args = HashMap::new();
  406. args.insert("kind".to_string(), to_value("tags").unwrap());
  407. args.insert("lang".to_string(), to_value("fr").unwrap());
  408. let res = static_fn.call(&args).unwrap();
  409. let res_obj = res.as_object().unwrap();
  410. assert_eq!(res_obj["kind"], to_value(tags_fr.kind).unwrap());
  411. assert_eq!(res_obj["items"].clone().as_array().unwrap().len(), 1);
  412. assert_eq!(
  413. res_obj["items"].clone().as_array().unwrap()[0].clone().as_object().unwrap()["name"],
  414. Value::String("Programmation".to_string())
  415. );
  416. // and errors if it can't find it
  417. let mut args = HashMap::new();
  418. args.insert("kind".to_string(), to_value("something-else").unwrap());
  419. assert!(static_fn.call(&args).is_err());
  420. }
  421. #[test]
  422. fn can_get_taxonomy_url() {
  423. let mut config = Config::default();
  424. config.slugify.taxonomies = SlugifyStrategy::On;
  425. let taxo_config = TaxonomyConfig {
  426. name: "tags".to_string(),
  427. lang: config.default_language.clone(),
  428. ..TaxonomyConfig::default()
  429. };
  430. let taxo_config_fr = TaxonomyConfig {
  431. name: "tags".to_string(),
  432. lang: "fr".to_string(),
  433. ..TaxonomyConfig::default()
  434. };
  435. let library = Library::new(0, 0, false);
  436. let tag = TaxonomyItem::new("Programming", &taxo_config, &config, vec![], &library);
  437. let tag_fr = TaxonomyItem::new("Programmation", &taxo_config_fr, &config, vec![], &library);
  438. let tags = Taxonomy { kind: taxo_config, items: vec![tag] };
  439. let tags_fr = Taxonomy { kind: taxo_config_fr, items: vec![tag_fr] };
  440. let taxonomies = vec![tags.clone(), tags_fr.clone()];
  441. let static_fn = GetTaxonomyUrl::new(&config.default_language, &taxonomies);
  442. // can find it correctly
  443. let mut args = HashMap::new();
  444. args.insert("kind".to_string(), to_value("tags").unwrap());
  445. args.insert("name".to_string(), to_value("Programming").unwrap());
  446. assert_eq!(
  447. static_fn.call(&args).unwrap(),
  448. to_value("http://a-website.com/tags/programming/").unwrap()
  449. );
  450. // works with other languages
  451. let mut args = HashMap::new();
  452. args.insert("kind".to_string(), to_value("tags").unwrap());
  453. args.insert("name".to_string(), to_value("Programmation").unwrap());
  454. args.insert("lang".to_string(), to_value("fr").unwrap());
  455. assert_eq!(
  456. static_fn.call(&args).unwrap(),
  457. to_value("http://a-website.com/fr/tags/programmation/").unwrap()
  458. );
  459. // and errors if it can't find it
  460. let mut args = HashMap::new();
  461. args.insert("kind".to_string(), to_value("tags").unwrap());
  462. args.insert("name".to_string(), to_value("random").unwrap());
  463. assert!(static_fn.call(&args).is_err());
  464. }
  465. const TRANS_CONFIG: &str = r#"
  466. base_url = "https://remplace-par-ton-url.fr"
  467. default_language = "fr"
  468. [translations]
  469. [translations.fr]
  470. title = "Un titre"
  471. [translations.en]
  472. title = "A title"
  473. "#;
  474. #[test]
  475. fn can_translate_a_string() {
  476. let config = Config::parse(TRANS_CONFIG).unwrap();
  477. let static_fn = Trans::new(config);
  478. let mut args = HashMap::new();
  479. args.insert("key".to_string(), to_value("title").unwrap());
  480. assert_eq!(static_fn.call(&args).unwrap(), "Un titre");
  481. args.insert("lang".to_string(), to_value("en").unwrap());
  482. assert_eq!(static_fn.call(&args).unwrap(), "A title");
  483. args.insert("lang".to_string(), to_value("fr").unwrap());
  484. assert_eq!(static_fn.call(&args).unwrap(), "Un titre");
  485. }
  486. #[test]
  487. fn error_on_absent_translation_lang() {
  488. let mut args = HashMap::new();
  489. args.insert("lang".to_string(), to_value("absent").unwrap());
  490. args.insert("key".to_string(), to_value("title").unwrap());
  491. let config = Config::parse(TRANS_CONFIG).unwrap();
  492. let error = Trans::new(config).call(&args).unwrap_err();
  493. assert_eq!("Failed to retreive term translation", format!("{}", error));
  494. }
  495. #[test]
  496. fn error_on_absent_translation_key() {
  497. let mut args = HashMap::new();
  498. args.insert("lang".to_string(), to_value("en").unwrap());
  499. args.insert("key".to_string(), to_value("absent").unwrap());
  500. let config = Config::parse(TRANS_CONFIG).unwrap();
  501. let error = Trans::new(config).call(&args).unwrap_err();
  502. assert_eq!("Failed to retreive term translation", format!("{}", error));
  503. }
  504. }